[Vuejs]-Better way to control watching values for Vue.js

0👍

It should be possible to do this without using watch at all. Instead you can use a computed property with get and set to intercept changes.

export default {
  name: 'app',

  data () {
    return {
      rawValue: null
    }
  },

  computed: {
    value: {
      get () {
        return this.rawValue
      },

      set (value) {
        localStorage.setItem('value', value)
        this.rawValue = value
      }
    }
  },

  mounted () {
    this.rawValue = +localStorage.getItem('value') || 0
  }
}

The rest of the code should then access value, not rawValue, such that changes will be saved.

I’ve also tweaked the reading of the value out of localStorage to be +localStorage.getItem('value') || 0. Based on your default value I’ve assumed that you want to store a number but localStorage will store that as a string.

It should also be possible to move the code in mounted into the data function. e.g.:

data () {
  return {
    rawValue: +localStorage.getItem('value') || 0
  }
}

This would also be viable with your original code and would provide an alternative way to solve the problem. If you set the initial value from localStorage in data it wouldn’t trigger the watch.

Leave a comment