vuex的使用介绍

项目中新增vuex可以使用命令

git add vuex

vuex是专门为vue.js应用程序开发的状态管理方式。
vuex有一个核心就是store(仓库 )。vuex的核心有state、mutation、action。
state包含了全部的应用层级状态.
state的改变,主要通过commit一个mutation。Mutation里的函数必须为同步,如果是异步 需要使用dispatch一个action。

新建一个store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1
  },
  mutations: {
    increment(state){
      state.count ++ 
    },
    decrement(state){
      state.count --
    }
  },
  actions: {
    increment:({commit})=>{
      commit('increment')
    },
    decrement:({commit})=>{
      commit('decrement')
    } 
  },
})

在main.js引入

import Vue from 'vue'
import App from './App.vue'
import store from './store/modules/index'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

模板






mapMutation

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

你可能感兴趣的:(vuex的使用介绍)