Vue:添加新反应性属性的不同选项?

问题描述

我试图了解添加反应性属性的不同方法。我知道我无法将属性直接添加到根级别,因此我在我的数据中设置了一个 user 对象:

data() {
   return {
       user: {
       }
   }
}

虽然是我感到困惑的地方,因为文档说使用 Vue.set 是向对象添加新的反应性属性方法,所以在这个例子中: Vue.set(this.user,'first_name','Bob')

但是,我尝试了一种不同的方法并制作了一个触发方法的按钮,并在其中执行了以下操作:

testFunc() {
    let names = ["Bob","Vin","Mark"]
    this.user.test_property = names[Math.floor(Math.random() * names.length];
}

这奏效了。我在 Vue Dev 工具中进行了测试,看到属性 test_property 添加到对象中,并且每次单击按钮时都会更改它。如果 Vue.set() 是创建新的响应式属性的唯一方法,为什么这会起作用?

最后,我注意到如果我执行以下 <input v-model="user.other_new_property" />,这也会跟踪新属性的变化......我也不知道为什么会这样。vue

解决方法

看起来您使用的是带有选项 api 的 Vue v2。在这种情况下,您只需在您的方法中执行 this.property_name = value; 并从您的模板访问它。

,

当然this.user.test_property可以给对象添加属性test_property。但是这个属性不是反应性的。

new Vue({
  el: '#app',data() {
    return {
      user: {}
    }
  },created() {
    this.user.name = 'a name'
  },methods: {
    changeName () {
      this.user.name = 'b name'
    },changeAge () {
      this.user.age = '23'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p>{{ user.name }}</p>
  <input v-model="user.age" />

  <button @click="changeName">click me to change name</button>
  <button @click="changeAge">click me to change age</button>
</div>