1.组件封装
子组件wxml
<button>我是子组件</button>
<view>我是父组件传的参数{{phone}}</view>
<button bindtap="sendFatherVal">传值给父组件</button>
子组件json
{
"component": true,
"usingComponents": {}
}
直接放在app.json里面注册 可以在所有的页面中都使用该组件,而不用单独引入更方便
"usingComponents": {
"btn": "/components/button/button"
}
父组件使用
//父组件给子组件传值
<button bindtap="sendVal">传值给子组件</button>
<btn id="child" phone="{{phone}}" bind:getChildVal="getChildVal" model:my-value="{{name}}"></btn>
//js
sendVal(e){
this.setData({
phone:5555,
name:'zs
})
},
getChildVal:function(e){
console.log(e.detail);
},
//调用子组件方法
wx.nextTick(()=>{
this.selectComponent('#child')&&this.selectComponent('#child').childFun()
})
/*model:my-value="{{pageValue}}"自定义组件触发双向绑定 */
//子组件
<input type="text" model:value="{{myValue}}"/>
//behaviors 是用于组件间代码共享的特性,类似于一些编程语言中的 “mixins” 每个组件可以引用多个 behavior ,behavior 也可以引用其它 behavior 。
var myBehavior = require('my-behavior')
Component({
/**
* 组件的属性列表
*/
behaviors: [myBehavior],
properties: {
//获取父组件的传值
myValue:String,
phone:{
type:Number,
value:0,
//监听传递过来的属性,立即执行
observer:(newVal,oldVal)=>{
console.log(newVal)
console.log(oldVal)
}
}
},
//监听值,对象,对象中的属性,多个数据变化 且立即执行
observers: {
'myValue'(val){
console.log('observers-myValue', val)
},
'myValue,num'(val,val1){
console.log('多个数据监听',val,val1)
}
},
data: {
},
methods: {
//传值给父组件
sendFatherVal(){
this.triggerEvent('getChildVal','我是从子组件过来的')
},
childFun(){
console.log('子组件方法')
}
}
})
子组件加载完成就执行某个方法
可以写在组件的生命周期函数 attached()中
lifetimes: {
attached: function () {
//在组件实例进入页面节点树时执行
// 默认联动显示北京
var id = address.provinces[0].id
this.setData({
provinces: address.provinces, // 34省
citys: address.citys[id], //默认北京市辖区
areas: address.areas[address.citys[id][0].id]
})
},
detached: function () {
// 在组件实例被从页面节点树移除时执行
},
},