2017-10-24 11 views
1

私は、ユーザーが認証されているかどうかをチェックすることによって、私のルートを守るためにしようとしていますが、これは例のルートである:Vuex VUEルータでの名前空間のモジュールゲッターにアクセス

{ 
    path: '/intranet', 
    component: search, 
    meta: { requiresAuth: true }, 
    props: { 
    tax: 'type', 
    term: 'intranet-post', 
    name: 'Intranet' 
    } 
}, 

そして、私はこのようにガードを設定しています:

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 

    let authenticated = this.$store.getters['auth/getAuthenticated']; 

    if (!authenticated) { 
     next({ 
     path: '/login', 
     query: { redirect: to.fullPath } 
     }) 
    } else { 
     next() 
    } 
    } else { 
    next() 
    } 
}) 

これは、認証のためのvuexモジュールです:

import Vue from "vue"; 

export default { 
    namespaced: true, 
    state: { 
    authenticated: !!localStorage.getItem("token"), 
    token: localStorage.getItem("token") 
    }, 
    mutations: { 
    login: function(state, token){ 
     state.authenticated = true; 
     state.token = token; 
    }, 
    logout: function(state){ 
     state.authenticated = false; 
     state.token = ''; 
    } 
    }, 
    actions: { 
    login: function({commit}, token){ 
     localStorage.setItem('token', token); 
     commit('login', token); 
    }, 
    logout: function({commit}){ 
     localStorage.removeItem("token"); 
     commit('logout'); 
    } 
    }, 
    getters: { 
    getToken: (state) => state.token, 
    getAuthenticated: (state) => state.authenticated, 
    } 
} 

しかし、私はそれがあるように認証ゲッターにアクセスしようとすると、ルートガードに表示されるエラー:

Cannot read property 'getters' of undefined

どうしたらいいですか?この問題を解決するにはどうすればよいですか?

+0

あなたは 'router.beforeEach'を使うファイルから完全なコードを投稿できますか? – Thaadikkaaran

答えて

1

this.$store.gettersにアクセスしようとすると、this.$storeが未定義であるというエラーメッセージが表示されるため、ストアが初期化されていないか、ルータ内で設定されているように設定されているようです。 .getters['name/getter']を使用して名前空間ゲッターにアクセスすること自体が正しいです。

いくつかのチュートリアルの後、私は私の店を定義store.jsを持って、その後、私はこのように私のrouter.jsでそれをインポートします。

import store from './store' 

、その後storeの代わりthis.$storeに直接アクセス:

let authenticated = store.getters['auth/getAuthenticated']; 

私は問題はthis.$storeが自動的にVue-Componentsに追加されていると思いますが、ルータは実際にはコンポーネントではないため、$storeがありませんメンバー。ストアをインポートすると、これを回避できます。

関連する問題