【问题标题】:Does Vue recalculate computed property if nested data is updated?如果更新嵌套数据,Vue 是否会重新计算计算属性?
【发布时间】:2021-08-31 05:25:57
【问题描述】:

这个answer 提到如果嵌套对象更新,更新的属性不会更新。真的吗? 在这个guide 中找不到太多内容。

在这个例子中:

data() {
    return {
        example: [
          { 
           myArray : ['foo1', 'bar1'] 
           myObject: {
               "foo2": "bar2",
               "foo3": {
                    "foo4": "bar4"
          }
        ]
    },
computed: {
    sameExample() {
        return this.example
    }
}
      

对示例嵌套数据的任何更改会触发 Vue 重新计算属性吗?

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    对于 Vue 2,旧答案是正确的,但对于 Vue 3,这些反应性警告已得到解决,因此您可以更新嵌套数据,它会重新评估计算属性,如下所示:

    const {
      createApp
    } = Vue;
    const App = {
    
      data() {
        return {
          example: [{
            myArray: ['foo1', 'bar1'],
            myObject: {
              "foo2": "bar2",
              "foo3": {
                "foo4": "bar4"
              }
            }
          }]
        }
      },
      computed: {
        sameExample() {
          return this.example[0].myArray.join()
        }
      },
      methods: {
        addItem() {
          this.example[0].myArray.push("test")
        }
      }
    
    
    
    }
    const app = createApp(App)
    app.mount('#app')
    <script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>
    
    <div id="app">
      {{sameExample}}
    
      <button @click="addItem">add item</button>
    </div>

    【讨论】:

      【解决方案2】:

      您链接的问题/答案是错误的。

      当嵌套属性更改时,Vue 2 会更新计算。这不是反应性警告,因为它有效,并且在文档中的任何地方都没有提到它以及任何其他反应性警告。

      我在这里更改了 Boussadjra 对 Vue 2 的回答,它的工作原理完全相同。

      const {
        createApp
      } = Vue;
      const App = {
      
        data() {
          return {
            example: [{
              myArray: ['foo1', 'bar1'],
              myObject: {
                "foo2": "bar2",
                "foo3": {
                  "foo4": "bar4"
                }
              }
            }]
          }
        },
        computed: {
          sameExample() {
            return this.example[0].myArray.join()
          }
        },
        methods: {
          addItem() {
            this.example[0].myArray.push("test")
          }
        }
      
      
      
      }
      const app = new Vue(App)
      app.$mount('#app')
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      
      <div id="app">
        {{sameExample}}
      
        <button @click="addItem">add item</button>
      </div>

      【讨论】:

        猜你喜欢
        • 2020-09-09
        • 2019-10-03
        • 1970-01-01
        • 2019-10-25
        • 1970-01-01
        • 2019-10-19
        • 2021-03-20
        • 2019-06-18
        • 2015-01-28
        相关资源
        最近更新 更多