3

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

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

从这里开始,我感到困惑,因为文档说 usingVue.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

4

2 回答 2

0

当然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>

于 2021-03-01T06:04:30.343 回答
0

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

于 2021-03-01T05:25:45.713 回答