Vue.js computed property not updating

早过忘川 提交于 2019-12-04 02:00:49

I've ran into similar issue before and solved it by using a regular method instead of computed property. Just move everything into a method and return your ret. Official docs.

You need to assign a unique key value to the list items in the v-for. Like so..

<ClassView :klass-raw="klass" :key="klass.id"/>

Otherwise, Vue doesn't know which items to udpate. Explanation here https://vuejs.org/v2/guide/list.html#key

If your intention is for the computed property to update when project.classes.someSubProperty changes, that sub-property has to exist when the computed property is defined. Vue cannot detect property addition or deletion, only changes to existing properties.

This has bitten me when using a Vuex store with en empty state object. My subsequent changes to the state would not result in computed properties that depend on it being re-evaluated. Adding explicit keys with null values to the Veux state solved that problem.

I'm not sure whether explicit keys are feasible in your case but it might help explain why the computed property goes stale.

Vue reactiviy docs, for more info: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

If you add console.log before returning, you may be able to see computed value in filteredClasses.

But DOM will not updated for some reason.

Then you need to force to re-render DOM.

The best way to re-render is just adding key as computed value like below.

<div
  :key="JSON.stringify(filteredClasses)" 
  v-for="(klass, classIndex) in filteredClasses"
>
  <ClassView
    :key="classIndex"
    :klass-raw="klass"
  />
</div>

Caution:

Don’t use non-primitive values like objects and arrays as keys. Use string or numeric values instead.

That is why I converted array filteredClasses to string. (There can be other array->string convert methods)

And I also want to say that "It is recommended to provide a key attribute with v-for whenever possible".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!