您的位置:首页 > 产品设计 > UI/UE

关于对vuex使用过程中的一些心得体会

2017-08-26 22:25 671 查看
关于对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定义的方法',{最好提交对象上去});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue vuex