Vue.js computed property not updating

前端 未结 7 788
猫巷女王i
猫巷女王i 2020-12-29 22:36

I\'m using a Vue.js computed property but am running into an issue: The computed method IS being called at the correct times, but the value returned by the computed

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 22:56

    If you are adding properties to your returned object after vue has registered the object for reactivity then it won't know to listen to those new properties when they change. Here's a similar problem:

    let classes = [
        {
            my_prop: 'hello'
        },
        {
            my_prop: 'hello again'
        },
    ]
    

    If I load up this array into my vue instance, vue will add those properties to its reactivity system and be able to listen to them for changes. However, if I add new properties from within my computed function:

    computed: {
        computed_classes: {
            classes.map( entry => entry.new_prop = some_value )
        }
    }
    

    Any changes to new_prop won't cause vue to recompute the property, as we never actually added classes.new_prop to vues reactivity system.

    To answer your question, you'll need to construct your objects with all reactive properties present before passing them to vue - even if they are simply null. Anyone struggling with vues reactivity system really should read this link: https://vuejs.org/v2/guide/reactivity.html

提交回复
热议问题