[Vuejs]-Vue computed methods can't change data using setter in template

1👍

Mutating a prop locally is considered an anti-pattern

However, you can use the .sync modifier as shown below, but you can’t set the prop to null because you are specifying that it has to be an Object type.

Vue.component('my-component', {
  template: `<div>{{ userDataTest }}</div>`,
  props: {
    exampleData: {
      type: Object,
      required: true
    }
  },

  computed: {
    userDataTest: {
      get: function() {
        return this.exampleData
      },
      set: function(newValue) {
        this.$emit('update:exampleData', newValue)
      }
    }
  },

  mounted() {
    setTimeout(() => {
      console.log('Change now!')
      this.userDataTest = {}
    }, 2500)
  }
})

new Vue({
  el: '#app',

  data() {
    return {
      exampleData: {
        foo: 'bar'
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <my-component :example-data.sync="exampleData"></my-component>
</div>

2👍

It seems you’re trying to set the computed property’s value by returning a new value, but Vue doesn’t actually check the setter’s return value. Perhaps you were trying to proxy a data variable through a computed property. If so, the setter should set that data variable in the setter body.

For instance, your component could declare a data variable, named userData, which always has the latest value of the exampleData prop through a watcher:

export default {
  props: {
    exampleData: Object
  },
  data() {
    return {
      userData: {}
    }
  },
  watch: {
    exampleData(exampleData) {
      this.userData = exampleData
    }
  },
}

Then, your template and computed prop would use userData instead:

<template>
  <div>{{ userData }}</div>
</template>

<script>
export default {
  //...
  computed: {
    userDataTest: {
      get() {
        return this.userData
      },
      set(newValue) {
        this.userData = newValue
      }
    }
  }
}
</script>

Edit Setting data through computed prop

👤tony19

Leave a comment