computed property set not called in Vue

后端 未结 6 2182
没有蜡笔的小新
没有蜡笔的小新 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:09

    I'm not familiar if there's a computed set method that could work here, but there's a few other approaches to solving the problem.

    If you want a singular getter for mutating the data, you can use an event based method for setting the data. This method is my favorite:

    export default {
      template: `
          
    {{options.test}}
    `, data() { return { optionsData: { test: false } } }, computed: { options: { get() { return this.optionsData; }, }, }, methods: { setOptions(options) { this.$set(this, "optionsData", { ...this.optionsData, ...options }) } } }

    If you're not really doing anything in the get/set you can just use the data option

    export default {
      template: `
          
    {{options.test}}
    `, data() { return { options: { test: false } } } }

    Then there's also the option of get/set for every property

    export default {
      template: `
          
    {{test}}
    `, data() { return { optionsData: { test: false } } }, computed: { test: { get() { return this.optionsData.test; }, set(value) { this.optionsData.test = value } }, }, }

提交回复
热议问题