美文网首页Vue.js专区Web前端之路让前端飞
通过Vue.set给对象的对象赋值出现的诡异问题

通过Vue.set给对象的对象赋值出现的诡异问题

作者: 李佳明先生 | 来源:发表于2019-06-22 23:39 被阅读9次

    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,当触发buttonclick事件后,会有什么变化?

    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)))
    },
    

    本文属于作者原创,转载请注明出处。

    相关文章

      网友评论

        本文标题:通过Vue.set给对象的对象赋值出现的诡异问题

        本文链接:https://www.haomeiwen.com/subject/tgjbqctx.html