在src目录下面,新建一个store文件夹,目录结构如下
image.png
1、index文件
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from 'store/mutations'
import state from 'store/state'
import getters from 'store/getters'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
getters
})
2、state文件
const userInfo = JSON.parse(window.localStorage.getItem('user-info')) || ''
const user = {
isLogin: userInfo.isLogin ? userInfo.isLogin : false,
username: userInfo.username ? userInfo.username : '',
token: userInfo.token ? userInfo.token : ''
}
export default {
haveTabbar: true,
cartList: JSON.parse(window.localStorage.getItem('cart-lists')) || [],
searchLists: JSON.parse(window.localStorage.getItem('search-lists')) || [],
user
}
3、mutation文件(计算新的值)
export default{
//修改state的方法
}
4、getters文件
export default {
totalCount (state) {
if (state.user.isLogin === false) {
return 0
} else {
return state.cartList.reduce((result, list) => {
result += list.count
return result
}, 0)
}
},
totalPrice (state) {
return state.cartList.reduce((result, list) => {
if (list.isChecked) {
result += list.count * list.price
}
return result
}, 0)
},
totalCheckCount (state) {
return state.cartList.reduce((result, list) => {
if (list.isChecked) {
result += list.count
}
return result
}, 0)
},
changeAllState (state) {
if (state.cartList.length === 0) {
return false
} else {
return state.cartList.every(list => list.isChecked === true)
}
}
}
网友评论