Vuex
1. 什么是Vuex?
vuex :是一个专为vue.js开发的状态管理器,采用集中式存储的所有组件状态,通过vuex我们可以解决组件之间数据共享的问题,后期也方便我们管理以及维护
2.Vuex由五部分组成
- state: 存放状态,例如你要存放的数据
- getters: 计算属性,可以通过this.$store.getters来获取存放在state里面的数据
- mutations: 改变状态,唯一能改变state的状态就是通过提交mutations来改变,this.$store.commit()
- actions: 异步操作,异步的mutations,可以通过dispatch来分发从而改变state
- modules:模块化管理store(仓库),每个模块拥有自己的 state、mutation、action、getter
3.基本使用
通过在根目录下新建一个store文件夹,里面创建一个index.js文件,最后在main.js中引入,并挂载到实例上,之后那个组件中需要用到vuex就调用就可以了。
4.高级用法-数据持久化
问题:vuex里面存放的数据,页面一经刷新会丢失
解决方法:
- 存放在localStorage或者sessionStorage里面,进入页面时判断是否丢失,丢失再去localStorage或者sessionStorage里面取;
2)在vuex中可以通过安装vuex-persist 插件,进行持久化的配置就行
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState({
storage: sessionStorage,
key: "token"
})]//会自动保存创建的状态。刷新还在
})
5.高级用法-辅助函数(语法糖)
1. 有那几个辅助函数(4大金刚)
mapState ,mapActions,mapMutations,mapGetters
- 辅助函数可以把vuex中的数据和方法映射到vue组件中。达到简化操作的目的
- 如何使用:
<template>
<div id="">
{{ token }}
{{ token - x }}
</div>
</template>
<script>
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
import {createNamespacedHelpers} from 'vuex'
const {mapState:mapStateUser,mapActions:mapActionUser,mapMutations:mapMutaionuser} = createNamespacedHelpers('user')
const {mapState:mapStateCart,mapActions:mapActionCart,mapMutations:mapMutaionCart} = createNamespacedHelpers('cart')
export default {
name: '',
data() {
return {}
},
computed: {
...mapState({
token: 'token'
}),
...mapGetters(['token-x']),
...mapSateUser(['userid']),
...mapStateCart({cartid:'userid'})
},
//生命周期 - 创建完成(访问当前this实例)
created() {
this.setToken('123456')
},
//生命周期 - 挂载完成(访问DOM元素)
mounted() {},
methods: {
...mapActions({
setToken: 'setToken'
}),
...mapMutations(['SET_TOKEN']),
...mapMutaionUser({
setId:"setToken"
})
}
}
</script>