【问题标题】:Vue: different options to add a new reactive property?Vue:添加新反应属性的不同选项?
【发布时间】:2021-05-30 15:58:17
【问题描述】:

我正在尝试了解添加反应性属性的不同方法。我知道我无法将属性直接添加到根级别,因此我在数据中设置了 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 开发工具中进行了测试,看到属性 test_property 添加到对象中,并且每次单击按钮时都会更改它。如果 Vue.set() 是创建新的响应式属性的唯一方法,为什么这会起作用?

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

【问题讨论】:

    标签: vue.js vuejs2 vue-devtools


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 2019-04-06
        • 1970-01-01
        • 2019-02-05
        相关资源
        最近更新 更多