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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章