Blues Clues
Blues Clues

Reputation: 1858

How to access mapState property inside the method

How can I access the count property inside the method when I use vuex? Please see my code below.

Code screenshot: enter image description here

Error

[Vue warn]: Computed property "count" was assigned to but it has no setter.

Upvotes: 0

Views: 873

Answers (2)

geauser
geauser

Reputation: 1025

The mapState you wrote is inside a computed block. By default computed values are read-only, but you can make them read/write by giving them a setter (ie a function to call when modifying the computed value):

computed: {

  count: {
    get() { return this.$store.state.count; },
    set(newValue) {
      // This will most likely throw a warning, as it is bad practise.
      this.$store.state.count = newValue;
    }
  }

}

https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

Upvotes: 1

Zulqarnain Haider
Zulqarnain Haider

Reputation: 79

You can access computed properties just like you access your data properties in a component. But since you are mapping the state in this case. You should not increment or alter its value directly inside the component. Instead, you should dispatch an action with the updated/incremented value and use mutation to mutate the value of the count property in the state object. More detail https://vuex.vuejs.org/guide/mutations.html#commit-with-payload

Upvotes: 1

Related Questions