![](/img/trans.png)
[英]Vue - Is it fine to store a value in session storage rigth from the main.js file?
[英]How to access store getter updated value from main.js file in vue app?
我正在嘗試從main.js
文件訪問更新的 vuex getter 以檢查用戶是否已登錄。 基於此,我將用戶帶到登錄頁面。 在 main.js 文件中,我只是像這樣訪問存儲 getter。
var router = new VueRouter({...})
router.beforeEach((to, from, next) => {
console.log(store.getters['general/isUserLoggedIn'])
next()
})
general是模塊名稱。
但是當簡單地記錄store
時,它會顯示 object 的更新值。 但是當記錄store.getters['general/isUserLoggedIn']
它顯示初始 state 值。 為什么它不提供更新的價值。 這是正確的做法還是有任何替代方法。
更多細節
在store.js文件中
import Vue from 'vue'
import Vuex from 'vuex'
import general from './modules/general'
import other from './modules/other'
Vue.use(Vuex)
export const store = new Vuex.Store({
modules: {
general,
other
},
plugins: [],
strict: process.env.NODE_ENV !== 'production'
})
通過在App.vue文件中調用 api 狀態檢查用戶是否登錄
axios.get('/api/profile').then((response) => {
if (response.data.status === 'success') {
this.setUserLoggedIn(true)
}
})
通用模塊中的actions.js
setUserLoggedIn ({ commit }, data) {
commit(types.SET_USER_LOGGED_IN, data)
}
通用模塊中的mutation.js
const mutations = {
[types.SET_USER_LOGGED_IN](state, data) {
state.isUserLoggedIn = data
}
}
在初始導航中,防護中的登錄尚未完成,這就是您在控制台中看不到該值的原因。 它僅在記錄store
時才出現,因為它是在記錄后不久設置true
,並且當您記錄對象/數組然后單擊以查看它們的屬性時,控制台會自行更新。
解決競爭條件的一種方法是在登錄完成時重定向到主頁:
axios.get('/api/profile').then((response) => {
if (response.data.status === 'success') {
this.setUserLoggedIn(true)
this.$router.push('/'); // Route to home page once login is complete
}
})
在此之前,如果用戶未登錄,則重定向到登錄:
router.beforeEach((to, from, next) => {
const isLoggedIn = store.getters['general/isUserLoggedIn'];
if(!isLoggedIn) {
return next('/login');
}
next()
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.