vuex(概念、几部分组成、map高级语法、数据持久化)
1.vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储和管理程序的所有组件的数据
vuex实现组件件通信是在大型项目中使用。
2.几部分组成
1.state 存储数据 在组件中的使用 this.
s
t
o
r
e
.
s
t
a
t
e
.
属
性
名
2.
m
u
t
a
t
i
o
n
s
直
接
操
作
s
t
a
t
e
中
的
数
据
在
组
件
中
的
使
用
t
h
i
s
.
store.state.属性名 2.mutations 直接操作state中的数据 在组件中的使用 this.
store.state.属性名2.mutations直接操作state中的数据在组件中的使用this.store.commit(“方法名”,参数)
3.actions 可以实现异步操作 在actions中操作mutations中的数据 在组件使用 this.
s
t
o
r
e
.
d
i
s
p
a
t
c
h
(
"
方
法
名
"
,
参
数
)
4.
g
e
t
t
e
r
s
g
e
t
t
e
r
s
类
似
于
计
算
属
性
可
以
对
s
t
a
t
e
中
数
据
进
行
逻
辑
计
算
在
组
件
中
t
h
i
s
.
store.dispatch("方法名",参数) 4.getters getters类似于计算属性可以对state中数据进行逻辑计算 在组件中 this.
store.dispatch("方法名",参数)4.gettersgetters类似于计算属性可以对state中数据进行逻辑计算在组件中this.store.getters.方法名
5.modules 将state分模块
3.数据持久化
vuex里面存放的数据,页面一经刷新会丢失:
解决办法: 存放在localStorage或者sessionStorage里面,进入页面时判断是否丢失,丢失再去localStorage或者sessionStorage里面取;
在app.vue根组件的created里面判断是否丢失,在进行上面的操作;
vuex-的数据持久化下载的插件:
cnpm i vuex-persistedstate -S
并在store.js引入
import createPersistedState from 'vuex-persistedstate'
export default new Vuex.Store({
state,
getters,
mutations,
actions,
plugins: [createPersistedState()]
)}
4.map高级语法
1.语法糖,四大金刚辅助函数:mapState,mapActions,mapMutations,mapGetters
当一个组件需要多个状态是,这些状态都声明成计算属性过于冗长。于是有了辅助函数。
2.使用map
先通过导入…辅助函数,然后在注册一下 同时也得注册里面的值,就可以使用了
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
computed:{
...mapState({
a:"a", // "a" 指的是state中的a
b:"b"
}),
...mapGetters({
Val:'newVal' // 可以重新命名
})
}
methods:{
...mapActions({
getSync:'getSyncNum'
})
...mapMutations({
increament:"increament"
})
}
template
{{a}} {{b}}
{{getSync(1)}}
<button @click='increament(1)'></button>