vue-----vuex

使用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中的值的使用方式一致

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值