19.使用Vuex进行全局静态管理

2019-06-11  本文已影响0人  面具猴

1.依赖
npm install vuex --save
2.src下创建目录store
store下创建文件index.js
内容为:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
});
export default store

这样就可以全局使用vuex了
3.使用方式和Vuex.Store中定义的内容有关
State:基础数据

const store = new Vuex.Store({
  state: {
    count: 1
  }
});

组件中引用

{{this.$store.state.count}}

4.Getters:对数据操作后返回

const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getStateCount: function (state) {
      return state.count + 1;
    }
  }
});

组件中调用

{{this.$store.getters.getStateCount}}
  1. Mutations:对数据进行操作
const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {
      state.count = state.count + 1;
    },
    reduce(state) {
      state.count = state.count - 1;
    }
  }
});

组件中调用

//template中
    <div>{{this.$store.state.count}}</div>
    <el-button @click="handleAdd">+</el-button>
    <el-button @click="handleReduce">-</el-button>
//script中
    methods: {
      handleAdd() {
        this.$store.commit("add");
      },
      handleReduce() {
        this.$store.commit("reduce");
      }
    }
  1. Actions:对操作进行封装
    并不建议直接调用Mutations,在Actions中封装Mutations再调用:
  actions:{
    addFunc(context){
      context.commit("add");
    },
    reduceFunc(context){
      context.commit("reduce");
    }
  }

组件中调用

      handleAdd() {
        // this.$store.commit("add");
        this.$store.dispatch("addFunc");
      },
      handleReduce() {
        // this.$store.commit("reduce");
        this.$store.dispatch("reduceFunc");
      }
上一篇下一篇

猜你喜欢

热点阅读