1、安装vuex
npm install vuex --save
2、创建store文件夹
-
创建index.js
import Vue from 'vue' import Vuex from 'vuex' import app from './module/app' import user from './module/user' import getters from './getter' Vue.use(Vuex) const store = new Vuex.Store({ modules:{ app, user }, getters }) export default store;
-
创建app.js 、user.js、getter.js
import {ADD,DEC} from './mutatin-type' const app={ //state指的是app中的属性值、保存着所有的全局变量 state:{ a:2, user:{ id:0, name:'' } }, getters:{ myA(state){ return "a:"+state.a; } }, mutations:{ [ADD](state,n){ state.a+=n; }, [DEC](state,n){ state.a-=n; }, setUser(state){ state.user.id=20161350; state.user.name='lh' } }, actions:{ mySetUser(context){ context.commit('setUser'); //就是调用mutations中的setUser方法 }, myadd(context,n){ context.commit(ADD,n) //就是调用mutations中的ADD方法 }, mydec(context,n){ context.commit(DEC,n) 就是调用mutations中的DEC方法 } } } export default app;
const user={ state:{ user:{ id:20161350, name:'卢航' } }, getters:{ }, mutations:{ setUser(state){ state.user.id=20161350; state.user.name='lh' } }, actions:{ mySetUser(context){ context.commit('setUser'); } } } export default user;
const getters = { user: state => state.user.user, } export default getters
-
在main.js中引入store
import Vuex from 'vuex' import store from './store' Vue.use( Vuex ); new Vue({ el: '#app', router, store, //引入store components: { App }, template: '<App/>' })
-
在xxx.vue文件中引入getter state actions里面的内容
-
getter 、mapState
import {mapState,mapMutations,mapActions,mapGetters} from 'vuex' import store from '../store' computed:{ //引入state中的app中的a,然后直接在div中直接使用 ...mapState({ a:state=>{ return state.app.a } }), ...mapGetters(["myA","user"]), //在div中直接使用 },
-
引入mapActions
methods:{ //...mapMutations(["add","dec"]), ...mapActions(["myadd","mydec","mySetUser"]), add(){ this.myadd(5); }, dec(){ this.mydec(5); }, setUser(){ this.mySetUser(); } }
-