什么是vuex
- Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。Vuex背后的基本思想,就是前面所说的单向数据流。下图就是Vuex实现单向数据流的示意图。
vuex由五部分组成
- 分别是:state,actions,mutations,getters,modules
state | 用于存储公共的数据 |
---|---|
mutations | 唯一可以改变state的地方 |
getters | 相当于vuex的计算属性 |
actions | 异步操作,在组件中使用是$store.dispath(’’) |
modules: | store的子模块,用于开发大型项目管理而使用的 |
如何让在页面中使用vuex
// 在页面中获取vuex中的数据,有三种方式,分别是
// 建议使用第三种
<template>
<div>
// 第一种:直接在标签使用
<p>{{$store.state.data}}</p>
// 第二种
<p>{{data}}</p>
// 第三种
<p>{{data}}</p>
</div>
</template>
data(){
return {
// 第二种
data:this.$store.state.data
}
}
// 第三种
computed: {
data(){
return this.$store.state.data
}
}
// store/index.js
export default new Vuex.Store({
state: {
data:'hello world'
},
})
在页面中调用mutaions中的方法
this.$store.commit('change',this.text)
在页面中调用actions中的方法
this.$store.dispatch('change',this.text);
高级用法
数据持久化
- 使用数据持久化插件
安装依赖 cnpm i vuex-persistedstate --save
在vuex中引入
在store/index.js中
// 首先引入
import persist from 'vuex-persistedstate'
// 使用 跟state,mutations同级
plugins: [persist()]
辅助函数(语法糖)
- 有四个辅助函数,分别是:
- mapActions
- mapGetters
- mapMutations,
- mapState