computed property set not called in Vue

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

    Instead of a computed getter/setter, use a local data prop, initialized to the target localStorage item; and a deep watcher (which detects changes on any subproperty) that sets localStorage upon change. This allows you to still use v-model with the local data prop, while observing changes to the object's subproperties.

    Steps:

    1. Declare a local data prop (named options) that is initialized to the current value of localStorage:
    export default {
      data() {
        return {
          options: {}
        }
      },
      mounted() {
        const myData = localStorage.getItem('my-data')
        this.options = myData ? JSON.parse(myData) : {}
      },
    }
    
    1. Declare a watch on the data prop (options), setting deep=true and handler to a function that sets localStorage with the new value:
    export default {
      watch: {
        options: {
          deep: true,
          handler(options) {
            localStorage.setItem('my-data', JSON.stringify(options))
          }
        }
      },
    }
    

    demo

提交回复
热议问题