- 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)))
- },
来源: http://www.jianshu.com/p/87dd31e4ab21