1、基础步骤不在一步步展示
首先下载项目依赖:
vuex
**npm install --save vuex**
2、项目目录结构如下:
3、新建store文件夹,并新建actions.js getters.js mutations.js state.js type.js index.js文件。
4、构建actions.js getters.js mutations.js state.js type.js index.js文件中代码:
index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
//绑定store
Vue.use(Vuex);
**// 这是一个vuex的插件 有很多优秀的插件可以引入,根据项目需要**
const syncStorage = (store) => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
// console.log(mutation, state)
window.localStorage.setItem('cart', JSON.stringify(state.count))
})
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
plugins:[syncStorage]
});
console.log(store)
export default store
type.js
export const SET_COUMT = 'SET_COUMT'
export const SET_COUMT_ADD = 'SET_COUMT_ADD'
export const SET_COUMT_REDUCE = 'SET_COUMT_REDUCE'
state.js
const state = {
count:0
}
export default state
actions.js
import * as TYPES from './types';
const actions = {
ADD1000(vuex) {
// axios.get("/customer/user_info").then(res => {
// commit(TYPES.SET_COUMT, res.data);
// });
vuex.commit(TYPES.SET_COUMT_ADD, 1000);
},
REdUCE1000(vuex) {
// axios.get("/customer/user_info").then(res => {
// commit(TYPES.SET_COUMT, res.data);
// });
vuex.commit(TYPES.SET_COUMT_REDUCE, 1000);
}
}
export default actions
mutations.js
import * as TYPES from './types';
const mutations = {
[TYPES.SET_COUMT](state, v) {
state.count = v;
},
[TYPES.SET_COUMT_ADD](state,v) {
if(v){
state.count += v
}else{
state.count ++
}
},
[TYPES.SET_COUMT_REDUCE](state,v) {
if(v){
state.count -= v
}else{
state.count --
}
}
}
export default mutations
getters.js
const getters = {
docount:(state,getters) => {
return state.counts
}
}
export default getters
5、文件搞定,运行项目 点击试试效果吧。
欢迎star本人github:https://github.com/flyku