官网上描述:
在index.page(父)页面与test.component(子)互相动态传值,使用.sync:
canshu1为父传到子的值,canshu2为子传到父的值
父:canshu1在父页面通过点击testt方法动态变化,canshu2在父页面使用watch监听改变
{{item}}
rr{{canshu1}} {{canshu2}}
data = {
canshu1:'55',
canshu2:0
};
watch = {
canshu2 (newValue, oldValue) {
console.log(`canshu2: ${oldValue} -> ${newValue}`)
}
};
methods = {
testt: function(type){
this.canshu1 = type;
}
};
在test.component组件中使用props接收,
子:使用watch动态监听canshu1变化,canshu2通过getProps方法动态变化:
test.component{{canshu}}
点击我
props = {
canshu1: {
type: String, //限制类型为字符
default: null //默认值为null
},
canshu2: {
type: Number, //限制类型为数字
default: 0, //默认值为0
twoWay: true //true表示在子组件里更改了canshu2值, 父组件也会同步更改
},
};
watch = {
canshu1 (newValue, oldValue) {
console.log(`canshu1: ${oldValue} -> ${newValue}`)
}
};
methods = {
getProps(){
var num = this.canshu2 //获取props值
this.canshu2 = ++num
}
};
结果:
注意这里有一个坑:在微信开发工具的预览模式下:
minified必须为false,否则父子之间的动态传值将失效。
另外wepy仅支持小程序的生命周期:onLoad、onReady函数