先引用vuex
首先用npm
安装Vuex
npm i vuex
新建文件夹store,建store.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// 全局变量
state: {
user: undefined
},
// 修改全局变量必须通过mutations中的方法
// mutations只能采用同步方法
mutations: {
login (state, payload) {
state.user = payload
},
loginOut (state) {
state.user = undefined
}
},
// 异步方法用actions
// actions不能直接修改全局变量,需要调用commit方法来触发mutation中的方法
actions: {
login (context, payload) {
context.commit('login', payload)
},
loginOut (context) {
context.commit('logout')
}
}
})
export default store
登录界面
先引用store.js
import store from '../store/store.js'
修改Login.vue
,在login
方法中,通过dispatch
方法来调用actions
中的login
方法
login () {
this.$refs.loginForm.validate((valid) => {
if(valid){
if(this.user.name=="荔枝" && this.user.pass=="123"){
// dispatch异步采用Promise链式调用
this.$store.dispatch('login',this.user).then(()=>{
this.$notify({
message:'欢迎您' + this.user.name + '!',
type:'success',
duration: 3000
})
this.$router.replace('/')
})
}else{
this.$message({
type: 'error',
message: '用户名或密码错误',
showClose: true
})
}
}else{
return false;
}
})
///
}
主页面
最后修改Main.vue
,用户已登录的时候显示用户名和注销按钮,未登录时显示登录按钮
<template>
<div>
<h1>主页面</h1>
欢迎你!
<span v-if="user"> {{user.name}}
<el-button type="warning" @click="loginOut">注销</el-button>
</span>
<el-button v-else type="success" @click="login">点击登录</el-button>
</div>
</template>
<script>
import store from '../store/store.js'
export default {
computed:{
user(){
return this.$store.state.user;
}
},
methods: {
login () {
this.$router.push('/login')
},
loginOut(){
this.$store.dispatch('loginOut').then(()=>{
this.$router.push('/login')
})
}
},
store
}
</script>
运行结果
未登录
登录成功了