【问题标题】:Component doesn't react to property change [array member accessed by index]组件对属性更改没有反应[索引访问的数组成员]
【发布时间】:2017-11-29 06:55:36
【问题描述】:

我在根 Vue 实例中有一个方法可以更新同一 Vue 实例的“数据”对象中的一些数据(见下文)。

这是我在根 Vue 实例的方法对象中的函数

updateRecipe(newRecipe) {
   this.recipesArr[this.findRecipeIndex(newRecipe.id)] = newRecipe;
}

这是我在根 Vue 实例中的数据对象

data: {
   recipesArr: JSON.parse(localStorage.getItem("storedRecipes")) // this is an array filled with objects
}

然后我有一个 Vue 组件,它的“recipesarr”属性绑定到根实例的数据对象中的“recipesArr”。

这是我的 Vue 组件,名为“recipe-list”

<recipe-list
   v-bind:recipesarr="recipesArr">
</recipe-list>

不幸的是,这个 Vue 组件不会对我的“updateRecipe”函数对“recipesArr”所做的任何更改做出反应。为什么会出现这种情况?如何让它对根 Vue 实例中对“recipesArr”所做的更改做出反应?

如下图所示,“recipesarr”属性已更新;但是,当我将“servingsNum”从 4 更改为 2 时,Vue 组件不会更新。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    你们都解决了问题,但我们不妨把它写下来。 Vue cannot detect changes to array members when you access them directly by index. 使用 splice() 或 Vue.set() 修改数组成员,您的更改将被检测到。所以……

    updateRecipe(newRecipe) {
       // Don't do this.
       this.recipesArr[this.findRecipeIndex(newRecipe.id)] = newRecipe;
       // Do this instead !
       this.recipesArr.splice(this.findRecipeIndex(newRecipe.id),1,newRecipe);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2013-05-14
      相关资源
      最近更新 更多