반응형
Vuex 스토어/내비게이션 가드가 처음 작동하지 않음
사용자 대시보드에 사용자가 존재해야 계속할 수 있는 네비게이션 가드가 있습니다.
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
const user = JSON.parse(store.state.authenticatedUser)
if(user) {
console.log("Route accepted.")
next()
} else {
console.log("Route rejected.")
next('/')
}
}
}
]
})
로그인 폼에 디스패치하여 입수합니다.토큰 및 연관된 사용자를 반환하는 토큰.
<template>
<v-container>
<h1 class="display-2">Login</h1>
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-col cols="12" md="12">
<v-row align="center">
<v-text-field
v-model="email"
:rules=emailRules
label="Email"
required
dense
></v-text-field>
</v-row>
<v-row align="center">
<v-text-field
v-model="password"
label="Password"
required
dense
type="password"
></v-text-field>
</v-row>
</v-col>
<v-btn
@click="login"
>Login</v-btn>
</v-form>
</v-container>
</template>
<script>
export default {
data: () => ({
valid: true,
password: '',
email: '',
emailRules: [
v => !!v || 'Email is required.',
v => /.+@.+\..+/.test(v) || 'You have entered an invalid email.',
],
}),
methods: {
login() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password })
this.$router.push('dashboard')
}
}
}
</script>
actions: {
logout() {
this.commit('revokeUser')
this.commit('revokeToken')
},
obtainToken(random, payload) {
const data = {
email: payload.email,
password: payload.password
}
api.post(this.state.endpoints.obtainToken, data)
.then((response => {
this.commit('updateSessionUser', response.data.user)
this.commit('updateToken', response.data.token)
}))
.catch((e) => {
console.log(e)
})
},
클릭할 때submit
사용자는 취득되지만 사용자가 존재하지 않기 때문에 루트는 거부됩니다.클릭해야 합니다.submit
사용자가 두 번째로 접속할 수 있도록 합니다.dashboard
경로.
그래서 제가 결과를 통해 알 수 있는 것은$router.push
로서 발생하고 있다.obtainToken
일어나고 있기 때문에 그들은 경주를 합니다.사용자가 이미 존재하기 때문에 두 번째 로그인은 계속 진행됩니다.내가 여기서 뭘 잘못하고 있는 거지?
또한 router.push()가 약속의 해결로서 호출되도록 노력하고 있습니다.
login() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password })
.then(() =>
this.$router.push('dashboard')
)
}
이 문제는 에 있는 것 같습니다.login
방법.
login() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password })
this.$router.push('dashboard')
}
양쪽 콜을 동시에 실행합니다.토큰 콜을 취득하기 전에 사용자를 탐색하려고 했습니다.
login() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password })
.then(() =>
this.$router.push('dashboard')
)
}
토큰이 존재하면 대시보드로 이동할 때 토큰을 상태에서 가져올 수 있습니다.
부르기dispatch
비동기입니다.
라우터를 변경할 때는 아직 정의되어 있지 않습니다.
그래서 디스패치에 연락해서mounted()
다른 페이지를 이동하기 전에.
mounted() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password })
},
methods: {
login() {
this.$router.push('dashboard')
}
}
또는
methods: {
login() {
this.$store.dispatch('obtainToken', { email: this.email, password: this.password }).then(() => this.$router.push('dashboard'))
}
}
편집: 반환해야 합니다.promise
에obtainToken
이하와 같다.
obtainToken(random, payload) {
...
return api.post(this.state.endpoints.obtainToken, data) // just add `return`
...
}
언급URL : https://stackoverflow.com/questions/58360698/vuex-store-navigation-guard-doesnt-work-first-time
반응형
'programing' 카테고리의 다른 글
Composer 실행 시 xdebug 사용 안 함 (0) | 2023.01.17 |
---|---|
폼 제출과 같은 JavaScript 투고 요청 (0) | 2023.01.17 |
외부 키 제약 조건:업데이트 시 및 삭제 시 사용 시기 (0) | 2022.11.23 |
페이지 응답성을 높이려면 이벤트 핸들러를 '수동'으로 표시하십시오. (0) | 2022.11.23 |
PHP에서 개체의 보호된 속성을 가져오는 방법 (0) | 2022.11.23 |