store中的index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token:'',
},
mutations: {
// 用于修改token的值,起到监听的效果
setToken(state, token) {
state.token = token;
localStorage['token'] = token//同步存储token至localStorage
},
},
getters :{
//获取token的值
getToken(state) {
if (!state.token) {
state.token = localStorage.getItem('token')
}
return state.token
},
//把用户的token值设为空
setBlock(state) {
state.token=""
return state.token
}
},
actions: {
},
modules: {
}
})
把从后端请求成功的函数中写入
if(response.data.message=="true"){
//修改localStorage中的setToken的值和state中的token值都赋值为后端返回来的token值
this.$store.commit('setToken',response.data。token)
}
页面构造时把localStorage中的token值赋值给state中的token值
created(){
//调用了store中的取值的方法
this.$store.getters.getToken
}
该页面中的coputed计算函数
computed:{
//用计算函数双向绑定vuex中的token变量
userLogin() {
return this.$store.state.token;
}
},
绑定计算属性
<template>
<div style="color:skyblue" >{{userLogin}}</div>
</template>
页面中的监听事件,这里就可以写当用户状态变化时所需要执行的逻辑操作,这里的noLogin和isLogin是用来使块级元素是否显示,为用户展现出登录和未登录时不同界面效果
watch: {
//监听userlogin
userLogin(newVal) {
console.log('改变值:', newVal)
//为空即为不登陆状态
if( newVal===""|| newVal===null)
{
this.noLogin=true;
this.isLogin=false;
console.log(2)
}
//当其值不为空时表示用户登录,让页面显示用户登录这个状态
else{
this.noLogin=false;
this.isLogin=true;
this.userEmail=this.$root.EMILLOGIN
console.log(1)
}
}
},