在store文件夹下新建state.js,mutations.js,mutations-type.js,actions.js,getters.js

index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from "./state";
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
getters,
})
state.js
export default {
userInfo:{},
shopCart:''
}
mutations-type.js
//用户信息
export const SET_USERINFO = 'SET_USERINFO'
//加入购物车
export const ADD_TO_CART = 'ADD_TO_CART'
export const SELECTED_GOODS_COUNT = 'SELECTED_GOODS_COUNT'
mutations.js
import * as types from './mutations-types'
export default {
[types.SET_USERINFO](state, payload) {
// console.log(state)
state.userInfo = payload
},
[types.ADD_TO_CART](state, payload) {
state.shopCart = payload
},
}
getters.js
import { SELECTED_GOODS_COUNT } from './mutations-type'
export default {
SELECTED_GOODS_COUNT(state) {
// 3.1 取出state中的商品数据
let count = 0;
let shopCart = state.shopCart;
Object.values(shopCart).forEach((goods, index) => {
if (goods.checked) {
// 6.2删除选中商品
count++;
}
});
return count;
},
}
actions.js
mport {SET_USERINFO} from "./mutations-type"
export default {
async login({commit}) {
let userInfo = {name: 'Jone', age: 22}
commit(SET_USERINFO, userInfo)
}
}
在main.js引入
import store from './store/index'
使用
let userInfo = { name:'Tom',age:20 }
this.$store.commit('SET_USERINFO',userInfo)
网友评论