一、父子组件通信
父子组件通信的3种方式:① 属性绑定 ② 事件绑定 ③ 获取组件实例
1、属性绑定
实现父向子传值
,并且只能传递普通类型的数据
子组件在 properties
节点中声明对应的属性并使用
。
// 父组件的data节点
data:{num:33
}// 父组件的WXML结构
<my-test testNum="{{num}}"></my-test>// 子组件(test)的JS文件
Component({properties: {testNum:Number,},
})// 子组件的WXML文件
<view>父组件传递过来的值为:{{testNum}}</view>
2、事件绑定
实现子向父传值
,可以传任意类型的数据
步骤:
①父组件定义一个函数 → ②父组件WXML通过自定义事件形式引用1中的函数 → ③在子组件中,调用this.triggerEvent('自定义事件名称',{/*参数对象*/})
,将数据发送到父组件 → ④在父组件中通过e.detail
获取到子组件传递的数据
// 父组件定义函数
addCount(){console.log(111)
}// 父组件WXML通过自定义事件引用函数
<my-test bind:addCount="addCount"></my-test>
<my-test bindaddCount="addCount"></my-test>// 子组件调用this.triggerEvent()方法
<button bindtap="addCount">+1</button>
<view>子向父亲传递数据:{{count}}</view>methods: {addCount(){this.setData({count:this.data.count +1})this.triggerEvent("addCount",{value:this.data.count})}
}// 父组件通过e.detail获取数据
addCount(e){this.setData({count:e.detail.value})
}
3、获取组件实例
在父组件里调用 this.selectComponent("id或class选择器")
,获取子组件的实例对象,从而直接访问子组件的任意数据和方法。
// 父组件WXML结构
<my-test2 count = {{count}} bind:AddCount="addCount" class=".son"></my-test2>
<button bindtap="getChild">获取子组件实例</button>// 父组件方法
getChild(){const child = this.selectComponent('.son');child.setData({count:child.properties.count +1})child.addCount()}
二、behavior
behaviors 是小程序中,用于实现组件间代码共享
的特性,类似于 Vue.js 中的 “mixins”
1、工作模式
每个 behavior 可以包含一组属性、数据、生命周期函数和方法
。组件引用它时,它的属性、数据和方法会被合并到组件中
。
2、创建behavior
调用 Behavior(Object object) 方法
即可创建一个共享的 behavior 实例对象
// behavior.js文件
module.exports = Behavior({properties:{},data:{},methods:{}
})
3、导入并引用behavior
使用 require() 方法
导入需要的 behavior,挂载后即可访问 behavior 中的数据或方法
// 在自定义组件的js文件中导入并behavior模块
const myBehavior = require("../../behaviors/behavior");
// 引用behavior
Component({behaviors:["myBehavior"],
})
4、behavior中所有可用的节点
可用的节点 | 类型 | 是否必填 | 说明 |
---|---|---|---|
properties | Object Map | 否 | 同组件的属性 |
data | Object | 否 | 同组件的属性 |
methods | Object | 否 | 同自定义组件的方法 |
behaviors | String Array | 否 | 引入其他的behavior |
created | Function | 否 | 生命周期函数 |
attached | Function | 否 | 生命周期函数 |
ready | Function | 否 | 生命周期函数 |
moved | Function | 否 | 生命周期函数 |
detached | Function | 否 | 生命周期函数 |