[Nuxt] Update Vuex State with Mutations and MapMutations in Vue.js

You commit changes to state in Vuex using defined mutations. You can easily access these state mutations in your template using mapMutations. This lesson shows you have to wire together your Vue.js template with your Vuex store using mutations and mapMutations.

 

store/index.js:

import Vuex from 'vuex'

const store = () => new Vuex.Store({
  state: {
    counter: 0
  },

  mutations: {
    increment: (state) => {
      state.counter++
    },
    decrement: (state) => {
      state.counter--
    }
  }
})

export default store

 

pages/index.vue:

<template>
  <div>
    Counter: {{counter}}
    <button @click='increment'>+</button>  
    <button @click='decrement'>-</button>  
  </div>
</template>

<script>
  import { mapState, mapMutations } from 'vuex'

  export default {
    computed: {
      ...mapState({
        counter: (state) => state.counter
      })
    },

    methods: {
      ...mapMutations([
        'increment',
        'decrement'
      ])
    }
  }
</script>

 

posted @ 2017-07-24 15:59  Zhentiw  阅读(337)  评论(0)    收藏  举报