1. 组件的双向绑定
- 组件外部用 v-model 绑定
- 组件内部用
value
接收 - 组件内部监听
value
和副本currentValue
,在currentValue
发生变化的时候广播 input 事件,即可达到双向绑定的效果
watch: {
value() {
this.currentValue = this.value
},
currentValue(val) {
this.$emit("input",val);
},
},
2. 在组件中监听 prop 失效
解决办法:写成下面这种形式,使用 immediate
属性。
watch: {
loading: {
immediate: true,
handler(val){
if(val){
this.currentDisabled = true
}
},
},
},
原因:因为 watch 的一个特点是,最初绑定的时候是不会执行的,当 loading 值改变时才进行监听计算。而immediate: true
代表如果在 wacth 里声明了 loading 之后,就会立即先去执行里面的 handler 方法,如果为 false就跟我们以前的效果一样,不会在绑定的时候就执行。