天天看點

小程式元件通過behavior實作代碼重用behavior代碼共享(資料不會互相影響)

behavior代碼共享(資料不會互相影響)

be.js檔案

let beh = Behavior({

// 共享屬性

properties: {

name: {

type: String,

value: ‘malinshu’

},

sex: {

type: String,

value: ‘man’

}

},

// 共享資料

data: {

},

// 共享方法

methods: {

behTap(name, sex) {

this.setData({

name: name,

sex: sex

})

}

}

})

export {

beh

}

comp1元件1

js代碼:

import { beh } from ‘./be.js’ // 導入behavior.js

Component({

behaviors: [beh], // 繼承behavior.js裡面的properties,data,methods

properties: {

name:{

type:String,

value: ‘xiaoxiao’,

observer:(newv,oldv,path)=>{

console.log(newv,oldv,path)

// 輸出malinshu xiaoxiao[“name”]

}

}

},

methods: {

onTap(ev) {

let { name, sex } = ev.target.dataset

this.behTap(‘malinshu’, ‘man also’) // 通過this可以通路behavior.js裡面的内容

}

}

})

wxml代碼:

comp1:name:{名稱:{{ name }},性别{{ sex }}}

設定資料

comp2元件2

js代碼:

import { beh } from ‘./be.js’ // 導入behavior.js

Component({

behaviors: [beh], // 繼承behavior.js裡面的properties,data,methods

properties: {

},

methods: {

onTap(ev) {

let { name, sex } = ev.target.dataset

this.behTap(‘mamama’, ‘shushushu’) // 通過this可以通路behavior.js裡面的内容

}

}

})

wxml代碼:

comp2:name:{名稱:{{ name }},類型:{{ sex }}}

設定資料

在頁面中應用這兩個元件

小程式元件通過behavior實作代碼重用behavior代碼共享(資料不會互相影響)

繼續閱讀