Vue.js 2.0:组件不会更新怎么解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (408)

我使用Vue 2.0编写了以下页面,我想知道为什么我的组件不会在user_copy分配给user_edit时进行更新,而是在我仅仅分配用户字符串属性时进行更新?有没有办法让代码以最小的修改工作,还是应该使用完全不同的方法?

<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
.user {
    marign-bottom: 20px;
    border:1px solid gray;
    padding: 20px;
}
.user:hover {
    background: orange;
    cursor: pointer;
}
</style>
</head>
<body>
  <div id="app">
    <user v-for="user_obj in users" :key="user_obj.id" :user_obj="user_obj" :parent_edit="edit"></user>
    <div>
        <input type="text" v-model="user_edit.user"/> 
        <input type="button" value="reset" @click="reset"/>
    </div>
  </div>
<script> 
Vue.component("user", {
    props: ["user_obj", "parent_edit"],
    template: "<div @click='edit' class='user'>{{user_obj.user}}</div>",
    methods: {
        edit: function() {
            this.parent_edit(this.user_obj);
        }
    }
}); 

  users = [
    {
      "user": "user 1",
      "id": 123
    },
    {
      "user": "user B",
      "id": 1231
    },
    {
      "user": "user 1B",
      "id": 1232
    },
    {
      "user": "user 1C",
      "id": 1233
    }
    ];

  var app = new Vue({
    el: "#app", 
    data: function() {
        return {
            users: users,
            user_edit: { }, /* reference to currently edited user */
            user_copy: { }
        }
    }, 
    methods: {
        reset: function() {
            /*A: works */
            this.user_edit.user = this.user_copy.user;
            /*B: Wouldn't work:
            /* this.user_edit = this.user_copy; */
        },
        edit: function(user) {
            this.user_copy = JSON.parse(JSON.stringify(user));
            this.user_edit = user;
        }
    }
  });
</script>

</body>
</html>
提问于
用户回答回答于

this.user_edit仍然指向同一个对象。Vue并没有重新考虑这种变化。你应该深入复制Vue更新:

reset: function() {
   // Will work:
   this.user_edit = JSON.parse(JSON.stringify(this.user_copy))
}

扫码关注云+社区

领取腾讯云代金券