前言
一、vuex是什么?
vuex :是一个专为vue.js开发的状态管理器,采用集中式存储的所有组件状态,通过vuex我们可以解决组件之间数据共享的问题,后期也方便我们管理以及维护
它由五部分组成:
分别是:
state (用来存放数据)
actions (可以包含异步操作)
mutations (唯一可以修改state数据的场所)
getters (类似于vue组件中的计算属性,对state数据进行计算(会被缓存))
modules (模块化管理store(仓库),每个模块拥有自己的 state、mutations、actions、getters)
二、vuex的使用步骤
代码如下(示例):
在根目录下新建一个store文件夹,里面创建一个index.js文件,
最后在main.js中引入,并挂载到实例上,之后那个组件中需要用到vuex就调用就行
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//存放数据 this.$store.state.xxx
state: {},
// 唯一修改state的地方 this.$store.commit('事件名',参数)
mutations: {},
// 执行异步操作 this.$store.dispatch('事件名')
actions: {},
// 模块,每个模块拥有自己的state,mutations,actions,getters
modules: {},
// 计算state
getters:{} this.$store.getters.xxx
})
三、高级用法(持久化工具)
vuex持久化工具vuex-persistedState
可以解决页面刷新之后数据会丢失的问题
1.安装命令:
cnpm i vuex-persistedstate --save
注意:
-S 是–save的简写,意为:把插件安装到dependencies(生产环境依赖)中
-D是–save-dev的简写,意为:把插件安装到devDependencies(开发环境依赖)中
2.使用在store文件夹下面的index.js文件中引入
import persist from 'vuex-persistedstate'
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState({
storage: localStorage, // 定义数据存储的方式 值可以是localStorage 也可以是sessionStorage
// 定义需要指定存储的数据 因为正常工作中vuex不是每一条数据都需要存储 所以我们需要指定需要存储的数据
reducer(state) {
return {
goods: state.goods
}
})]
})
四、高级用法—辅助函数(语法糖)
辅助函数有如下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>
五、高级语法---- 模块化管理数据 (modules)
项目庞大,数据信息量特别大的时候,我们可以考虑分模块形式管理数据,比如user模块管理用户信息数据,cart模块管理购物车数据,shop模块管理商品信息数据。