猿问

Vue 反应性不会获取添加到数组元素的新属性

不确定我的解释是否正确,但我面临一个问题,我的模板元素之一没有对数组元素的添加属性做出反应。例如:


<div v-for="user in users"

     v-bind:key="user.id"

     v-bind:name="user.name">

     {{user.name}}

     <div class="warn" v-if="user.hasWarning">Warning!</div>

</div>

我试图在hasWarning: true添加到时显示警告user


data:() {

  users: [

    {id: 1, name: "Foo"}

  ]

},

methods:{

  showWarning: function(id) {

    users.forEach(user => {

      if (user.id == id) {

        user.hasWarning = true;

      }

    });

  }

}

我试着打电话showWarning(id),我确实看到hasWarning从控制台和 Vue 开发人员工具添加到用户,但它没有呈现<div class class="warn" v-if="user.hasWarning"..。如果我将我的用户设置为{id: 1, name: "foo", hasWarning: false},它似乎工作正常,但为什么它不适用于添加的属性?我应该完全避免它吗?


尚方宝剑之说
浏览 109回答 1
1回答

LEATH

您必须使用该方法this.$set来注册新属性。请参阅文档:https ://v2.vuejs.org/v2/api/#vm-set尝试这样的事情:<template>&nbsp; <div>&nbsp; &nbsp; <div v-for="user in users" v-bind:key="user.id" v-bind:name="user.name">&nbsp; &nbsp; &nbsp; {{ user.name }}&nbsp; &nbsp; &nbsp; <button @click="showWarning(user.id)">showWarning</button>&nbsp; &nbsp; &nbsp; <div class="warn" v-if="user.hasWarning">Warning!</div>&nbsp; &nbsp; </div>&nbsp; </div></template><script>export default {&nbsp; name: 'App',&nbsp; data: () => ({&nbsp; &nbsp; users: [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }],&nbsp; }),&nbsp; methods: {&nbsp; &nbsp; showWarning(id) {&nbsp; &nbsp; &nbsp; let user = this.users.find(user => user.id == id);&nbsp; &nbsp; &nbsp; this.$set(user, 'hasWarning', true);&nbsp; &nbsp; },&nbsp; },};</script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答