vue2(笔记)5.0 vuex
---手动安装,配置
---state(提供.使用数据)
示例代码片段:
state () {
return {
userIndex: getInfo()
}
},
store访问(不推荐):
辅助函数(推荐):
展开运算符写在computed计算属性里
使用分模块的情况下:
需要指定模块名
...mapState('cart', ['cartList']),
---mutations(只有他能修改state数据)
不推荐:
传参:
辅助函数(推荐):
展开运算符写在methods方法属性里
---actions(处理异步操作)
原生(不推荐):
context:上下意思 num:传递的值
context.commit:表示调用mutations的方法
辅助函数(推荐):
展开运算符写在methods方法属性里
---getters(类似于计算属性)
原生(不推荐):
辅助函数(推荐):
展开运算符写在computed计算属性里
---使用module,完整的包结构
---module(分模块使用)
核心概念:
使用module后的子模块映射:
模块名:modules/user
['xxx']:user下的属性
其他三个属性同理
示例代码(store/index.js):
import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/store/modules/user'
import cart from '@/store/modules/cart'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters: {
token (state) {
return state.user.userIndex.token
}
},
mutations: {
},
actions: {
},
modules: {
user,
cart
}
})
示例代码(store/modules/user.js):
// vuex-modulse里的user
import { getInfo, setInfo } from '@/utils/storage'
export default {
namespaced: true, // 命名空间开启
state () {
return {
userIndex: getInfo()
}
},
mutations: {
getuser (state, obj) {
state.userIndex = obj
setInfo(obj)
}
},
actions: {
logout (context) {
// 重置个人信息
context.commit('getuser', {})
// 重置购物车内容-----跨模块找购物车数据 赋空值, {root:true} 开启全局模式
context.commit('cart/setCartList', [], { root: true })
}
},
getters: {}
}