使用vuex来实现登录功能,并缓存登录状态
项目中安装vuex
npm install vuex --save
在main.js中引用
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
因为我的vuex的使用的就是store文件夹,所以就这样引用
在store组件当中使用modules划分对应的功能使用
为了让数据存储,不被刷新重置,在vuex中引用了vuex-persistedstate
安装方式:
npm install vuex-persistedstate --save
store组件中的index.js中这样写
import Vue from 'vue'
import Vuex from 'vuex'
import Login from "./modules/Login.js"
import VuexPersistense from 'vuex-persistedstate'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
Login
},
state: {},
mutations: {},
actions: {},
plugins: [VuexPersistense()]
})
在login.js中这样写,我这里主要是使用hasLogin的值,别的值都是装饰
const state = {
userInfo:{},
token:'',
hasLogin:false
}
const actions = {
login(context,payload){
context.commit('LOGIN')
}
}
const getters = {
login:state=>{
return state.hasLogin
}
}
const mutations = {
LOGIN(state,payload){
if(payload){
state.userInfo = payload.data
}
state.hasLogin = true
},
LOGINOUT(state,payload){
state.userInfo = {}
state.hasLogin = fale
}
}
export default {
state,
actions,
getters,
mutations
}
在登录的页面提交action的值,似的haslogin的值得以改变
this.$store.dispatch('login')
在我的页面中判断haslogin的值,当值为真时显示用户数据
import { mapGetters } from 'vuex'
computed:{
...mapGetters({
hasLogin:'login'
})
},
hasLogin直接在html中使用即可,和vue data中的值的使用方式一致