官网上描述:
在index.page(父)页面与test.component(子)互相动态传值,使用.sync:
canshu1为父传到子的值,canshu2为子传到父的值
父:canshu1在父页面通过点击testt方法动态变化,canshu2在父页面使用watch监听改变
<view>
<block wx:for="{{['爱奇艺','腾讯','优酷']}}" wx:for-item="item" wx:key="*this" >
<view bindtap="testt({{item}})">
{{item}}
</view>
</block>
rr{{canshu1}} {{canshu2}}
<test :canshu1.sync="canshu1" :canshu2.sync="canshu2" />
</view>
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方法动态变化:
<view class="body">
test.component{{canshu}}
<view id="tt {{canshu1}}" bindtap="getProps">点击我</view>
</view>
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
}
};
结果: