zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

VueJS in and with update State Vuex
2023-09-14 08:59:18 时间

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>