安装
npm i -S vuex@3.6.2
理念
借鉴了Flux数据流思想, 基于单向数据流
Action:视图层发出的动作信息,可以来自于用户交互,也可能来自于服务器响应
Dispatcher:派发器,用来接收 Actions 并执行相应回调函数
Store:用来存放应用的状态,一旦发生变化就会通知视图进行重绘
View:React 组件视图
state ==> 全局共享属性
getters ==> 针对于state数据进行二次计算,获取state
mutations ==> 存放同步方法的,唯一更改state的方法
actions ==> 存放异步方法的,并且是来提交mutations
modules ==> 把vuex再次进行模块之间的划分
mutations与actions对比
相同点:都可以存放全局方法,都不能return值
不同点:
mutations:同步
actions:异步,返回一个Promise对象,很难调试
理解:mutations是来修改state的值的,actions的作用是来提交mutations
使用
state使用:
this.$store.state.str // 可以直接修改数据
// 或者
{{ str }}
computed:{
...mapState(['str'])
}
this.str // 不能修改数据
getters使用:
getters: {
get_num(state) {
return state.num
},
},
this.$store.getters.getNum
// 或者
{{ getNum }}
computed:{
...mapGetters(['getNum'])
}
mutatioins使用:
mutations: {
add(state, value) {
state.num =+ value
},
},
this.$store.mutations.add
// 或者
{{ add }}
methods:{
...mapMutations(['add'])
}
// 或者
this.$store.commit('add', 1)
actions使用:
actions: {
addNumber(context, value) {
context.commit('add', value)
},
},
this.$store.actions.addNumber
// 或者
{{ addNumber }}
methods:{
...mapActions(['addNumber'])
}
this.$store.dispatch('addNumber', 1)
modules使用:
业务模块的封装
export default {
namespaced:true, // getters等相关属性都需要加上命名空间了
state: { // 数据 8
orderCount:99
},
getters: { // 获取数据的快捷方式 5
getOrderCount(state){
return state.orderCount
}
},
mutations: { // 变化 => 改变数据 => 记录devTool的快照 8
addOrderCount(state){
state.orderCount++;
}
},
// 一系列业务逻辑 + 多个数据的修改
actions: { // dispatch => actions => 改变数据 8
async addOrder(store,payload){
return await store.dispatch('asyncTest')
}
},
}
modules: { // 业务模块的封装
order
}
this.$store.state.order.orderCount
this.$store.getters.order.getOrderCount
this.$store.getters['order/getOrderCount'] // namespaced:true情况下
this.$store.mutations.order.addOrderCount
this.$store.actions.order.addOrder
// 或者
{{ $store.state.order.orderCount }}
{{$store.state['order/orderCount']}}
{{ getOc }}
{{ aoc }}
{{ doAo }}
computed:{
...mapState(['order/orderCount']),
// ...mapGetters(['order/getOrderCount']),
// ...mapGetters({
// 'getOc':'order/getOrderCount'
// }),
...mapGetters({
'getOc':function(state) {
return state.order.getOrderCount;
},
})
},
methods:{
// ...mapMutations(['order/addOrderCount']),
// ...mapActions(['doAo':'order/addOrder'])
...mapMutations({
'aoc': 'order/addOrderCount'
}),
...mapActions({
'doAo':'order/addOrder'
})
}
// 或者
this.$store.state.order.orderCount
this.getOc
this.$store.commit('order/addOrderCount')
let res = this.$store.dispatch('order/addOrder', 5)
this.aoc()
let res = await this.doAo(5)
自动导入vuex模块
// Webpack单独实现的API 操作文件
let modulesFn = require.context('./modules', true, /\.js$/);// 目录 是否子文件 处理的文件特点
// console.log('modules:',modulesFn('./order.js')) // .default拿到数据
// console.dir(modulesFn); // 可以看到所有的方法
const reg = /\.\/(.*?)\.js$/;
modulesFn.keys().forEach(filePath => {
let moduleObj = modulesFn(filePath).default; // fn(相对路径):{default:ModuleObj}
moduleObj.namespaced = true;
const regRes = reg.exec(filePath);
const moduleName = regRes && regRes[1];
moduleName && store.registerModule(moduleName,moduleObj)
});
订阅
store.subscribe((mutation, state) => {
console.log('数据改变了.. 这里可以做本地额存储')
});
vuex持久化存储
安装:
npm i -S vuex-persistedstate
使用:
// 引入插件
import createPersistedState from "vuex-persistedstate";
/* vuex数据持久化配置 */
plugins: [
createPersistedState({
// 存储方式:localStorage、sessionStorage、cookies
storage: window.localStorage
// 存储的 key 的key值
key: "project_store",
render(state) {
//要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
return { ...state };
}
})
]