vuex的使用

1.安装:

npm install vuex --dev

2.在src下创建一个store文件夹,在文件夹下创建如下几个文件

image.png

3.在main.js中引入

import store from './store/index'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: ''
})

4.store各文件配置

store->index.js

import Vue from "vue";
import Vuex from "vuex";
import state from './state';
import getters from './getters';
import actions from './actions';
import mutations from './mutations';

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  actions,
  getters,
  mutations
})

store -> state.js

const state = {
  num:0,
  name:'啦啦啦',
  age:11
}
export default state;

store->mutations-type.js

export const SUM_ADD = 'SUM_ADD';
export const Sum_MINUS = 'Sum_MINUS';
export const NAME = 'NAME';

store->mutations.js

import * as types from './mutations-type';

const mutations = {
  [types.SUM_ADD](state,payLoad){
    state.num += payLoad.unit;
  },
  [types.Sum_MINUS](state,payLoad){
    state.num -= payLoad.unit;
    if( state.num < 0 ){
      state.num = 0;
    }
  },
  [types.NAME](state,payLoad){
    state.name = payLoad.txt;
  },
}
export default mutations;

store->getters.js

const getters = { //公共的计算属性
  getName:function (state){
    return state.age >= 18 ? '成年' : '未成年'
  }

}
export default getters;

store->actions.js

const actions = {
  changeName(content,payLoad){
    content.commit('NAME',payLoad)
  }

}
export default actions;

5.使用vuex

state / getter 以及辅助函数的使用

 
{{ $store.state.num }} {{$store.getters.getAge }}
import { mapState, mapActions, mapMutations,mapGetters} from "vuex"; 或者 computed:{ ...mapState({ num:state => state.num, name:state => state.name, }), ...mapGetters({age:'getAge'}), },

计算 mutations / actions 以及辅助函数的使用

 
    {{ num }}


  

import { mapState, mapActions, mapMutations,mapGetters} from "vuex";
methods:{
    ...mapMutations({
      addNum: "SUM_ADD",
      minusNum: "Sum_MINUS",
    }),
    ...mapActions({
      changeName:"changeName"
    }),
    /*addNum(unit){
      this.$store.commit('SUM_ADD',unit)
    },
    minusNum(unit){
      this.$store.commit('Sum_MINUS',unit)
    },*/
  /*  changeName(txt){
      this.$store.dispatch('changeName',txt)
    }*/
  },

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