*斜体样式vuex 是 vue 的状态管理工具 管理项目中的公共数据 能够在所有的组件中使用
一共有五大核心
state 存放公共数据的地方 通过 this.
s
t
o
r
e
.
s
t
a
t
e
.
x
x
x
调
用
m
u
t
a
t
i
o
n
s
修
改
s
t
a
t
e
的
地
方
只
有
这
里
能
修
改
通
过
t
h
i
s
.
store.state.xxx调用 mutations 修改 state 的地方 只有这里能修改 通过this.
store.state.xxx调用mutations修改state的地方只有这里能修改通过this.store.commit 调用
getters 相当于是之前的计算属性 通过 this.
s
t
o
r
e
.
g
e
t
t
e
r
s
调
用
a
c
t
i
o
n
s
执
行
异
步
操
作
的
地
方
通
过
t
h
i
s
.
store.getters 调用 actions 执行异步操作的地方 通过 this.
store.getters调用actions执行异步操作的地方通过this.store.dispatch 调用
modules 模块化
vuex 缺点就是刷新数据会丢失 我们可以保存本地存储 或者 安装 vuex 持久化插件 vuex-persist 去实现自动本地存储*
2.1vuex 的执行机制
我在项⽬当中如果要改变 state 的状态,我们⼀般是在组件⾥⾯调⽤ this.$store.dispatch ⽅式来触发 actions ⾥⾯的⽅法,在 actions
⾥⾯的⽅法通过 commit 来调⽤ mutations ⾥⾯定义的⽅法来改变 state,同时这也是 vuex 的执⾏机制
2.2 怎么开启严格模式
strict: true, 跟 state 同级的地方设置这个属性
开启完严格模式后 如果不是通过 mutation 修改的 state 就会报错
strict 严格模式只适合开启在开发环境下
2.3 modules
把仓库里的数据分模块管理
每个模块里又有四个核心 state mutations getters actions
然后引入仓库 并且在 modules 下注册模块
在定义的 modules 里开启一个命名
namespaced:true
export default {
computed: {
arr() {
return this.$store.state.a.arr;
//使用 模块a里的state数据arr
},
},
methods: {
add() {
this.$store.commit("a/add");
//调用a下面的add方法
},
},
};