data里边
obj:{a:{b:''}},
a:{b:''}
html里边
<input @input="input" type="text" v-model="a.b">
<button @click="ensure()"></button>
methods里边
ensure(){
Vue.set(this.obj,'a',this.a)
},
input(){
console.log(this.obj)
}
先试想一下,当在input里输入hello world
,当触发button
的click
事件后,会有什么变化?
console.log(this.obj)
//{a:{b:'hello world'}}
然后在input框里输入233333
(设想下,连续按下333333),这时候肯定会触发input
事件,那你觉得this.obj
会打印为多少呢?
大多数人猜想的结果是:
hello world
hello world
hello world
hello world
hello world
可能会出乎你的意料,但实际结果是:
hello world 2
hello world 23
hello world 233
hello world 2333
hello world 23333
其实导致出现这个问题的点很多人也曾了解过,却又有很多人没有想到这个点,就是引用类型的值之间相互赋值
的问题(复制的变量其中一个修改了对象
,另一个变量
也会受到影响
)
这里引用某大神的链接,此处不做过多解释
https://blog.csdn.net/weixin_42047144/article/details/80091349
所以正确操作为:
ensure(){
Vue.set(this.obj,'a',JSON.parse(JSON.stringify(this.a)))
},
本文属于作者原创,转载请注明出处。
网友评论