Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property was assigned to but it has no setter

Tags:

vue.js

vuex

What is the correct syntax/hooks to make this work for myVal?

My code looks like this:

<v-item-group v-model="myVal" ...

import { mapActions, mapGetters } from 'vuex'; 
export default {
  computed : {
     ...mapActions({
       myVal: 'myModulePath/setMyVal'
     }),
     ...mapGetters({
       myVal: 'myModulePath/getMyVal'
     }),
  },
}

The store looks like:

actions: {
  setMyVal({commit}, value){commit('someMutation',value);}
getters: {
  getMyVal: state => { return state.myVal;}

I'm not sure how to wire it so the 'setter' works and the error message goes away.

I've also tried this to no avail:

...mapState('myModulePath', ['myVal']) 
like image 448
ekjcfn3902039 Avatar asked Dec 20 '18 20:12

ekjcfn3902039


People also ask

Can we use setters and getters in computed properties?

Getters and setters in Swift are the methods a computed property uses to either set or get a value on-demand. A stored property stores a value for later use (for example, a variable that belongs to a class instance). A computed property does not store a value. Instead, it computes it only when requested.

Can we pass parameters to computed property?

For passing the parameters to the computed property, we just pass the parameters as we do for the function.

Why use computed property in Vuejs?

In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.

What is VUEX in VUE JS?

Vuex is a state management pattern + library for Vue. js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.


2 Answers

You need to define a single computed with a get and a set function. Maybe:

export default {
  computed : {
     myVal: {
        get() { return this.$store.getters.getMyVal; },
        set(newValue) { this.$store.dispatch('setMyVal', newValue); }
     }
  },
}
like image 178
Roy J Avatar answered Oct 09 '22 18:10

Roy J


You need to tell the vue component what to do when the computed property is assigned a new value

computed: {
     myVal: {
        get: () => this.$state.store.getters.myModulePath.getMyVal,
        set: (value) => this.$state.commit('someMutation', value )
    }
  }

Note that I use the setter instead of the action. Using an action in the computed property setter is a bad idea because actions are usually asynchronous and can cause headaches trying to debug the computed property later.

like image 15
jfadich Avatar answered Oct 09 '22 19:10

jfadich