关于对vuex使用过程中的一些心得体会
vuex是什么
是专为vue.js应用程序开发的状态管理模式
集中储存应用所有组件的状态
vuex的应用场景是在多个视图应用同一个状态且组件内嵌套关系比较复杂时vuex的核心概念
- Store储存状态(一个应用只能有一个store)
- State(集中管理应用状态的对象)
- Getters(获取组件内部的state并对其进行逻辑处理)
- Mutations(唯一修改state的回调函数)
- Actions(异步操作,提交Mutations,而不是直接改变State的状态)
- Modules(当应用的应用场景复杂时我们需要划分模块,分别管理各个组件的States)
详细介绍
如何使用vuex
安装vuex模块
npm install vuex --save
作为插件使用
vue.use(vuex)
注入根实例当中去
{
store
}
完整实例,新建store.js
import vue from 'vue'
import Vuex from 'vuex'
export const LOGIN_SUC = 'LOGIN_SUC';
export const SHOW_LOGIN = 'SHOW_LOGIN';
let store = new Vuex.store({
state: {
mobile: '',
password: '',
isShowLogin: false,
},
actions: {
addMyInfo({ commit } , loginInfo){
commit(LOGIN_SUC , loginInfo);
},
showLogin({ commit } , flag){
commit(SHOW_LOGIN , flag);
},
},
mutations: {
[LOGIN_SUC] (state , loginInfo) {
state.mobile = loginInfo.mobile;
},
[SHOW_LOGIN] (state , flag) {
state.isShowLogin = flag;
},
},
getters: {
getMsg(state){
return state.msg;
},
getMobile(state){
return state.mobile;
},
getIsShowLogin(state){
return state.isShowLogin
}
}
})
上面是一个简单实例
State
在实际项目过程中我们可以通过
this.$store.state.XXX
来获取state的状态
当然我们可以通过辅助函数mapState来简化操作
***不使用mapState时***
computed:{
isShowLogin:function(){
return this.$store.state.login.isShowLogin;
},
mobile: function () {
return this.$store.state.login.mobile;
}
}
***使用mapState时***
computed:{
...mapState({
isShowLogin: state => state.isShowLogin,
mobile: state => state.mobile,
}),
}
或者是字符串的值必须和state里面的值相同
computed:{
...mapState({
isShowLogin: 'isShowLogin',
mobile: 'mobile',
}),
}
- Motations
Motations是用来提交state并改变state的值this.$store.commit('Motations定义的方法',{最好提交对象上去});