0
I持っている私のvuejsのアプリvuexストアで次のアクション:データは、リダイレクト後にフェッチされていない
import { HTTP } from '@/services/http'
import router from '@/router'
export const actions = {
loginUser ({ commit }, params) {
HTTP.post('v1/login.json', { email: params.email, password: params.password })
.then(response => {
localStorage.setItem('access_token', response.data.token)
router.push({name: 'Hello'})
}).catch(error => {
commit('SET_LOGIN_ERROR', error.response.data.error)
})
},
myAccount ({ commit }, params) {
HTTP.get('v1/my_account.json', { headers: {'Authorization': 'Token token=' + localStorage.getItem('access_token')} })
.then(response => {
commit('SET_USER', response.data)
})
},
logout ({ commit }, params) {
HTTP.delete('v1/logout.json', { headers: {'Authorization': 'Token token=' + localStorage.getItem('access_token')} })
.then(response => {
localStorage.removeItem('access_token')
commit('SET_USER', {})
})
}
}
と、次のナビゲーションコンポーネント:
<template>
<div>
{{user.first_name}}
{{user.last_name}}
{{user.email}}
<button v-on:click="logout()" v-if="Object.keys(user).length !== 0">Logout</button>
</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
name: 'hello',
methods: {
...mapActions(['myAccount', 'logout'])
},
beforeMount: function() {
if (localStorage.getItem('access_token')) {
this.myAccount()
}
},
computed: {
...mapGetters(['user'])
}
}
</script>
このコンポーネントはApp.Vue内部に実装されています。
<template>
<div id="app">
<navigation></navigation>
<router-view></router-view>
</div>
</template>
<script>
import Navigation from './components/Navigation.vue'
export default {
components: { Navigation },
name: 'app'
}
</script>
問題は、以下の通りです:
- 私はログインページにアクセスし、有効なメールとパスワードを入力します。
- 私はルートパスにリダイレクトされました。 NaviagationコンポーネントはAPIからユーザーデータを取得する必要がありますが、それは行いません。
- F5でページを更新するナビゲーションコンポーネントはデータを正しく取得します。
どうすれば修正できますか?
の内側に、私はこの問題を推測しているように、この関数を呼び出す 'loginUser'アクションを持っている前に' beforeMount'フックが解雇されていることです'access_token'を設定してください。 'loginUser'アクションのポストリクエストの' then'コールバックに 'myAccount'をディスパッチすることができます。 – thanksd