jonjohval
jonjohval

Reputation: 25

Setting values with Vuex

I'm currently trying to learn Vuex.

I want so the the number-value increases each time you click on the element using a mutation(changeNumber).

let state = {
  counter: 0,
  someOtherValue: 'Text'
}

let changeNumber = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  changeNumber,
  state
})

Vue.component('counter-button', {
  computed: {
    counter() {
      return this.$store.state.counter
    }
  },
  template: `<input :value="$store.state.counter" @click="$store.commit('increment')" type="button">`
})

Vue.component('some-component', {
  computed: {
    someOtherValue() {
      return this.$store.state.someOtherValue
    }
  },
  template: '<div>{{ someOtherValue }}</div>'
})

new Vue({
  el: '#app',
  store,
  template: '<some-component></some-component>',

})

My code is corrected by a bot, and I get returned two errors. What's wrong with my code?

Err) clicking on the paragraph causes the number value to change
Err) triggering the changeNumber mutation causes the number value to change

Upvotes: 1

Views: 53

Answers (1)

Ronald
Ronald

Reputation: 1039

You should pass the mutations to the store under the key mutations instead of changeNumber. Note that in your code changeNumber is not the mutation, increment is the actual mutation.

let mutations = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  mutations,
  state
})

Upvotes: 1

Related Questions