Vuex 是什么
Vuex 是一个专为Vue.js应用程序开发的状态管理模式+库,它采用集中式存储管理 应用的所有状态,并以相应的规则保证状态以一种可预测的方式发生变化。
状态管理模式
状态:驱动应用的数据源; 视图:以声明方式将状态映射到视图; 操作:响应在视图上的用户输入导致的状态变化;
当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:
- 多个视图依赖于同一状态。
- 来自不同视图的行为需要变更同一状态。
对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。
安装
1 命令
npm install vuex --save
注意:安装兼容的版本
需要注意的是这里一定要加上 –save,因为这个包我们在生产环境中是要使用的
2 引用vuex
新建store 文件夹,在文件夹下新建 index.js 文件,在文件中引用vuex,如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
3 在main.js中引用,并添加到组件中,新增代码段如下:
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
使用
单向数据流
store: Vue Components --- dispatch ---- Actions--- commit ---Mutations --- mutate ---**State ** ---render --- Vue Components
简单应用
1 提交mutation
this.$store.state.loginState // 获取vuex 的state的状态loginState
this.$store.commit("loginState"); // 提交 mutation 的 loginState
state: {
loginState:false,
},
mutations: {
loginState(state){
if(state.loginState){
state.loginState=false;
}else{
state.loginState=true;
}
}
},
2 触发actions
// 派发动作,触发Actions
this.$store.dispatch('login','admin').then(()=>{
console.log("跳转路由");
}
).catch(
()=>{alert("用户名或密码错误")}
);
state: {
isLogin:false,
username:'' ,
},
// 修改状态
mutations: {
login(state,username){
state.isLogin=true;
state.username=username;
}
},
actions: {
// 参数1 是vuex 传递的上下文context ,可以从context中结构出 {commit ,dispatch,state} 等方法或状态
login({commit},username){
return new Promise((resolve,reject)=>{
console.log("actions");
// 1s中后如果用户名是 admin 则登录成功
setTimeout(() => {
if(username === 'admin'){
console.log(username);
commit('login',username); // 提交登录
resolve()
}else{
reject()
}
}, 1000);
})
},
},
模块化
使用modules定义多个子模块利于组件复杂状态
1 在store目录新建user.js
export default {
namespaced:true, // 命名空间, 避免命名冲突
// 存储状态
state: {
isLogin:false,
username:'' ,
},
// 修改状态
mutations: {
login(state,username){
state.isLogin=true;
state.username=username;
console.log("mutations");
console.log(state.isLogin);
},
loginOut(state){
state.isLogin=false;
console.log("mutations loginOut");
}
},
getters:{ // vuex的计算属性
welcome:state=>{ return state.username+"我回来了 getter的计算属性"}
},
// 处理异步
actions: {
// 参数1 是vuex 传递的上下文context ,可以从context中结构出 {commit ,dispatch,state} 等方法或状态
login({commit},username){
return new Promise((resolve,reject)=>{
console.log("actions");
// 1s中后如果用户名是 admin 则登录成功
setTimeout(() => {
if(username === 'admin'){
console.log(username);
commit('login',username); // 提交登录
resolve()
}else{
reject()
}
}, 1000);
})
},
},
}
修改store/index.js
import user from './user';
Vue.use(Vuex);
export default new Vuex.Store({
strict: true, // 设置严格模式
// 模块化
modules: {
user,
},
plugins:[persis,]
});
3 使用
// router/index.js
store.state.user.isLogin
// 派发
this.$store.dispatch('user/login', 'admin').then(() => {
const redirect = this.$route.query.redirect || '/'
this.$router.push(redirect)
}).catch(() => {
alert('用户名或密码错误')
});