1. 建立目录,在 src下面新建 store文件夹,然后新建一个 index.js
2. index.js 内容如下
说明:
- state是存放数据的地方, 使用 {{this.$store.state.count}}
- getters 相当于 computed方法 使用 {{this.$store.getters.getStateCount}}
- mutations 相当于methods方法, 但是不允许我们直接使用,要用下面的 actions调用这里的方法
- actions 外部调用的就是 actions下面的方法 , 使用 this.$store.dispatch('addFun'), 第一个context参数不要变,后面可以接自定义的参数
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
//创建Vuex实例
const store = new Vuex.Store({
state: {
count: 1,
typename: ""
},
getters: {
//类似 vue 的 computed
getStateCount(state) {
return state.count + 1;
}
},
mutations: {
//上面定义的state对象
add(state) {
state.count = state.count + 1;
},
//上面定义的state对象
reduction(state, n) {
state.count = state.count - n;
}
},
//注意actions,类似于 vue 里的 methods
actions: {
addFun(context) {
//接受一个与store示例具有相同方法的属性的 context对象
context.commit("add");
},
reductionFun(context, n) {
//接受一个与store示例具有相同方法的属性的context对象
context.commit("reduction", n);
}
}
});
export default store;
3. 在main.js 中引入
//引用vuex
import store from "./store";
/* eslint-disable no-new */
new Vue({
el: "#app",
router,
store, //使用store
components: { App },
template: "<App/>"
});
4. 如果感觉上面写的 {{this.$store.state.count}} 比较麻烦,可以用下面的方式
import { mapState, mapActions, mapGetters } from 'vuex';
----------
computed: {
...mapState({
count1: state => state.count
})
},
---------
{{count1}} 即可