computed property set not called in Vue

后端 未结 6 2059
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 16:19

According to the documentation I should be able to use computed properties as v-model in Vue as long as I define get/set methods, but in my case it doesn\'t wor

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 17:03

    The return value of Vue computed properties are not automatically made reactive. Because you are returning a plain object, and because you're assigning to a property within the computed property, the setter will not trigger.

    You have two problems you need to solve, one problem's solution is to store a reactive version of your computed property value (see Vue.observable()). The next problem is a bit more nuanced, I'd need to know why you want to hook in to the setter. My best guess without more information would be that you're actually looking to perform side-effects. In that case, you should watch the value for changes (see vm.$watch()).

    Here's how I'd write that component based on the assumptions above.

    export default {
      template: `
          
    `, computed: { options(vm) { return ( vm._internalOptions || (vm._internalOptions = Vue.observable({ test: false })) ) }, }, watch: { "options.test"(value, previousValue) { console.log("set") }, }, }

    If you need to trigger side-effects based on anything changing on options, You can deeply watch it. The biggest caveat though is that the object must be reactive (solved by Vue.observable() or defining it in the data option).

    export default {
      watch: {
        options: {
          handler(value, previousValue) {
            console.log("set")
          },
          deep: true,
        },
      },
    }
    

提交回复
热议问题