引入Vuex
1、首先用npm
安装Vuex
npm i vuex
2、在目录src/vuex/
下创建index.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
},
logout (state) {
state.user = undefined
}
},
// 异步方法用actions
// actions不能直接修改全局变量,需要调用commit方法来触发mutation中的方法
actions: {
login (context, payload) {
context.commit('login', payload)
},
logout (context) {
context.commit('logout')
}
}
})
export default store
3、在main.js
中引入之前的Vuex
配置
import store from './vuex'
...
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
登录界面
4、修改Login.vue
,在login
方法中,通过dispatch
方法来调用actions
中的login
方法
login () {
this.$refs.loginForm.validate((valid) => {
if (valid) {
if (this.user.name === 'admin' && this.user.pass === '123456') {
// dispatch采用Promise链式调用
this.store().dispatch('login', this.user).then(() => {
this.$notify({
type: 'success',
message: '欢迎您,' + this.user.name + '!',
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="logout">注销</el-button>
</span>
<el-button v-else type="success" @click="login">点击登录</el-button>
</div>
</template>
<script>
export default {
methods: {
login () {
this.$router.replace('/login')
},
logout () {
this.$store.dispatch('logout').then(() => {
this.$router.replace('/login')
})
}
},
computed: {
user () {
return this.$store.state.user
}
}
}
</script>
运行结果
未登录
已登录
小结
本阶段实现了页面间数据的共享,但是用户名和密码是直接写死在login方法中的,下个阶段将采用Node+Express搭建一个后台服务器,从后端进行用户名和密码的验证