最近在写项目的时候碰到一个奇怪的问题,记录下.
代码如下
<template>
<el-input class="bill-input" placeholder="请输入" v-model="data.charge"/>
</template>
<script>
data () {
return {
data: {
list: [],
charge:0,
},
}
mounted () {
this.init()
}
watch: {
"data.list": {
handler (newValue, oldValue) {
this.data.charge = 100
},
deep: true
},
'data.charge': {
handler (newValue, oldValue) {
console.log(newValue)
console.log(oldValue)
},
deep: true,
},
},
methods:{
init(){
this.data = {
list: [],
charge:0,
}
}
</script>
当页面初始化的时候,使this.data.list 改变,改变后执行监听在改变data.charge 此时所有监听都可以正常执行,然而在inpout 中改v-model 的值的时候,data.charge 是不能够被触发的
怀疑原因:视图渲染完毕后,数据才被动态赋值,此时视图层并没有更新该数据
解决办法:
watch: {
"data.list": {
handler (newValue, oldValue) {
//使用this.$set(obj, key, value)/vue.set(obj, key, value)
this.$set(this.data,'charge',100)
},
deep: true
},
'data.charge': {
handler (newValue, oldValue) {
console.log(newValue)
console.log(oldValue)
},
deep: true,
},
},