一、什么是Vuex
- Vuex是一个专为Vue.js应用程序开发的状态管理模式
- 采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
二、什么是状态管理模式
- 状态自管理应用包含以下几个部分
- state,驱动应用的数据源
- view,以声明方式将 state 映射到视图
- actions,响应在 view 上的用户输入导致的状态变化 - 什么时候使用
- 多个视图依赖同一个状态
- 来自不同视图的行为需要变更同一个状态 - 分模块,每个模块内需要包含
- state:初始化的数据
- actions:执行的异步操作
- mutations:唯一改变数据的方式
- namespaced:命名空间
三、分模块创建状态管理器
子模块user.js结构
// 初始化的数据
const state = {
loginState: localStorage.getItem('isLogin') || '',
userId: localStorage.getItem('userId') || '',
token: localStorage.getItem('token') || ''
}
// 执行的异步操作
const actions = {}
// 唯一改变数据的方式
const mutations = {
change_loginState (state, payload) {
state.loginState = payload
},
change_userId (state, payload) {
state.userId = payload
},
change_token (state, payload) {
state.token = payload
}
}
export default {
namespaced: true, // 改变mutations,可以直接使用user/change_loginState
state,
actions,
mutations
}
主模块引用user.js子模块
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
//在modules下进行引入
user
}
})
四、组件中使用Vuex
- 登录页面,登录成功之后改变Vuex的状态
- 组件内提交mutations,使用this.$store.commit()
// 登录成功之后,修改状态管理器的状态
this.$store.commit('user/change_loginState', 'ok')
this.$store.commit('user/change_token', res.data.token)
this.$store.commit('user/change_userId', res.data.id)
- 使用状态管理器中的状态,读取
// 状态管理器.状态.模块.属性
this.$store.state.user.loginState === 'ok'
this.$store.state.user.userId
五、mapState辅助函数的使用
- 主要用来获取状态,需要配合计算属性实现
- 组件中提前引入Vuex的辅助函数import { mapState } from 'vuex'
// 固定写法,利用解构赋值,获取state中的loginState,userId
computed: {
...mapState({
loginState: state => state.user.loginState,
userId: state => state.user.userId
})
}
- 可以直接使用
this.loginState
或this.userId
找到对应状态
组件的导航守卫中无法使用this找到实例
六、mapMutations辅助函数的使用
- 组件中提交mutations的简化写法,需要配合methods实现
- 组件中提前引入Vuex的辅助函数import { mapMutations } from 'vuex'
methods: {
...mapMutations({
change_loginState: 'user/change_loginState',
change_userId: 'user/change_userId',
change_token: 'user/change_token'
})
}
- 可以替换掉commit系列方法
// this.$store.commit('user/change_loginState', 'ok')
// this.$store.commit('user/change_token', res.data.token)
// this.$store.commit('user/change_userId', res.data.id)
this.change_loginState('ok')
this.change_token(res.data.token)
this.change_userId(res.data.id)