私はvuex
とvue-router
と一緒にVueJSを使用しています。私はvuex
モジュールが店舗に突然変異を起こしており、それを使ってユーザーが認証されているかどうかを判断しようとしています。beforeEachの間にvuexモジュール状態をvue-routerに渡す
ここで、私のコードは関連する部分に似ています。
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
router.beforeEach((to, from, next) => {
console.log(router.app) // prints a Vue$2 object
console.log(router.app.$store) // undefined
console.log(store.getters.isAuthenticated) // false
...
}
const app = new Vue({
store,
router,
...App
})
app.$mount('#app')
/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import core from './modules/core'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
core: core
}
})
export default store
/store/modules/core.js
import * as types from '../types'
import api from '../../api'
import router from '../../router'
const state = {
token: null,
user: null,
authenticated: false
}
const mutations = {
[types.LOGIN_SUCCESS] (state, payload) {
console.log('mutate')
state.token = payload.token
state.user = payload.user
state.authenticated = true
router.go('/')
}
}
const getters = {
isAuthenticated: state => {
return state.authenticated
}
}
const actions = {
[types.LOGIN] (context, payload) {
api.getToken(payload).then(response => {
context.commit(types.LOGIN_SUCCESS, response)
})
}
}
export default {
state,
mutations,
actions,
getters
}
LOGIN
アクションをトリガーするロジックに進み、突然変異が正しく実行されていることがわかります。core
モジュールのvuex状態を表示するとき、user
とauthenticated
の状態が正しく変更されています。
QUESTION
それは単にルータが.beforeEach
ループ内で実行されている時間によってロードされていない、このモジュールのように思えます。これは本当ですか?
「はい」の場合は、このような状況を処理する方法について他に何か提案がありますか? いいえ、私は間違って何をしていますか?
あなたは 'store.state.core.authenticated'をログインした場合、あなたは何を得るのですか? –
@francoisromain 'console.log(store.state.core.authenticated)'は 'false'を返す –
私は問題を理解したと思う。しかし、もう少し研究をするまで...自分の答えを投稿しません。状態は永続的ではなく、HTML5ローカルストレージのようなものを使用していないようです。したがって、各ページの読み込みでは、状態は空です。だから、私はそのような永続性を得るために私のユーザーをlocalstorage(または同等のもの)に移動させる必要があります。私は実行可能な解決策を持っており、これが最良の方法であると確信したときに投稿します。 –