一、安装vuex
npm i vuex
二、在main.js中引入
import Vuex from 'vuex'
import store from './store/user'
Vue.use( Vuex );
new Vue({
el: '#app',
router,
store,//全局引入
components: { App },
template: '<App/>'
})
三、新建文件夹store,建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use( Vuex );
// 全局变量,需要共享的属性
const state = {
isLogin:0,//登录状态(0:未登录,1登录)
username:'',//用户名
password:''//密码
}
// 修改全局变量必须通过mutations中的方法
// mutations只能采用同步方法
const mutations = {
changeLogin(state,payload){//第一个参数固定,第二个参数是action里调用方法时传递过来的
state.isLogin =payload.num
state.username=payload.admin.account
state.password = payload.admin.pass
}
}
// 异步方法用actions
// actions不能直接修改全局变量,需要调用commit方法来触发mutations中的方法
const actions = {
loginAction({commit},adminInfo){//adminInfo是登录接口里调用actions传递的
commit('changeLogin',{num:1,admin:adminInfo})//第一个参数是调用的方法名,第二个参数是传递给方法的参数,多个参数采用对象的方式
}
}
export default new Vuex.Store({
state,mutations,actions
})
下面我们来看看login.vue部分代码
一、先引入,采用结构赋值的方法,这样调用起来方便
import {mapState,mapActions} from 'vuex'
二、调用
computed:{
...mapState(['isLogin','username','password'])//使用拓展运算符,我们可以直接(this.方法名)调用,类似于调用data里面的属性
},
methods: {
...mapActions(['loginAction']),
login(){
this.$refs.ruleForm.validate((valid) => {
if (valid) {
axios.get('https://www.easy-mock.com/mock/5b7f7155ca80b23ee711cc71/example/login?account='+this.ruleForm2.account+'').then((result)=>{
if(result.data.data.Error==0){
// this.loginAction();
//如果需要向actions里面传值就手动调用,不能使用this.方法名 调用
this.$store.dispatch('loginAction',this.ruleForm2).then(()=>{ // dispatch异步采用Promise链式调用
this.$message({
message: '登录成功',
type: 'warning'
});
this.$route.push('/index')
})
}else{
this.$message({
message: '登录名或密码错误',
type: 'warning'
});
}
})
} else {
return false;
}
});
},