Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
- 集中式存储管理应用的所有组件的状态
- 保证状态以一种可预测的方式发生变化(按顺利对数据进行处理,不会有冲突)
- 简化Vue组件间通讯
核心概念与原理
1. state:页面状态管理容器对象。集中存储Vue components状态数据
2. mutations:状态改变操作方法,由actions中的commit(‘mutation 名称’)来触发。
是Vuex修改state的唯一推荐方法。该方法只能进行同步操作,且方法名只能全局唯一。
3. commit:状态改变提交操作方法。对mutation进行提交,是唯一能执行mutation的方 法。
4. actions:操作行为处理模块,由组件中的$store.dispatch('action 名称', data1)来触发。然后由commit()来触发mutation的调用 , 间接更新 state。
5. dispatch:操作行为触发方法,是唯一能执行action的方法。
6. getters:state对象读取方法。图中没有单独列出该模块,应该被包含在了render中,Vue Components通过该方法读取全局state对象。
使用步骤
下载安装:npm install vuex@next --save
新建 store文件夹,新建文件index.js
- 引入vuex import { createStore } from 'vuex'(解构createStore)
- 创建对象 const store=createStore({选项}),返回一个store对象
- 暴露出去store export default store
// 引入vue 解构出来
import {createStore} from 'vuex'
// 创建createStore实例,并返回store出来
const store = createStore({
// 状态数据,例如用户信息,数组
state:{
count:0 //状态数据
},
// 操作状态的方法,此时用大写
mutations:{
PLUS(state){
// 不能用this,默认有个staate
state.count++
},
MINUS(state){
state.count--
}
},
// 对象,通过actions通过commit来调用mutations
actions:{
// 把commit方法从对象参数中解构出来
plus({commit}){
commit('PLUS')
},
minus({commit}){
commit('MINUS')
}
},
// 获取值
getters:{
// 这里的count和行8的count不一样,搞不清楚用num代替
// count:(state)=>state.count,
num:(state)=>state.count
}
})
// 最后将其暴露出来,再mian.js中引入进来
export default store
此时我们在main.js中引入
此时其它的组件可以进行Count中的数据的操作
- 此时我们写一个vue文件
<template>
<div>
<h2>A组件</h2>
<!-- 显示状态数据,先绑定加1方法onPlus -->
<p>显示vuex状态count : {{num1}}</p>
<button type="button" @click="onPlus">加一</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
//methods - 创建方法
methods:{
onPlus(){
/*如何取到store中的数据?
我们集成,跟vue实例进行绑定,就像我们操作this.$router一样。
store是全局变量,可以通过this.$store来操作他
commit => mutations,用来触发同步操作的方法。
dispatch =>actions,用来触发异步操作的方法。
在store中注册了mutation和action,在组件中用dispatch调用action,
然后action用commit调用mutation。
*/
this.$store.dispatch('plus')
}
},
// 计算属性
computed:{
num1(){
return this.$store.getters.num
}
}
}
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
<!-- A组件可以操作Count,B也可以。实现组件的通信 -->
<!-- 组件需要集成进来,定义路由我们才可以访问,在组件中引用A -->
commit => mutations,用来触发同步操作的方法。
dispatch =>actions,用来触发异步操作的方法。
此时我们写好router里面的内容
{
// 路由懒加载A
path:'/a',
component:()=>import('../views/A.vue')
},
辅助函数map系列
mapActions
mapGetters
...mapActions [对象方法名]
...mapGetters[对象方法名]
引入辅助函数
import { mapGetters,mapActions } from 'vuex'
export default {
data() {
return {}
},
//methods - 创建方法
methods: {
// onMinus() {
// this.$store.dispatch('minus')
// },
// ...mapActions({
// onMinus:'minus'
// })
...mapActions(['minus'])
},
computed: {
// num(){
// return this.$store.getters.count
// },
// ...mapGetters({
//计算属性名: vuex中getters定义名称
// num:'count'
// })
// 当计算属性名和vuex中getters定义名称相同时,
// 使用如下方式实现
...mapGetters(['num']),
},
}
持久化存储
- 安装npm i vuex-persistedstate-S
- 引入ipmort createPersistedState from 'vuex-persistedstate'
module:当应用程序比较大的时候,把其拆分