【发布时间】:2020-07-06 18:02:15
【问题描述】:
我的问题是,当页面重新加载时,中间件先渲染,然后是 vuex;因此,当我想更改 vuex 中的值时,基于用户是否经过身份验证,中间件返回 vuex 的初始值。这意味着,如果用户通过身份验证,它首先显示 false,在渲染 vuex 之后,它再显示 true。但是到那时,中间件已经完成加载。这会导致在页面刷新时将用户重定向到登录页面。我的问题是,它们是我可以在中间件之前先加载 vuex 的一种方式吗?
这是中间件代码;
export default async function ({ store, redirect }) {
// If the user is not authenticated
const authenticated = await store.state.signup.authenticated
if (!authenticated) {
console.log(!authenticated)
return redirect('/login')
} else {
console.log('I am logged in')
}
}
这里是vuex代码;
import axios from 'axios'
export const state = () => ({
authenticated: false,
credential: null,
})
export const mutations = {
ADD_USER(state, data) {
state.credential = data
state.authenticated = true
},
LOGOUT(state) {
state.credential = null
state.authenticated = false
},
}
export const actions = {
async addUser({ commit }, data) {
try {
const response = await axios.post(
'http://localhost:8000/api/rest-auth/registration/',
data
)
commit('ADD_USER', response.data)
this.$router.push('/')
} catch (error) {
return console.log(error)
}
},
async addUserLogin({ commit }, data) {
try {
const response = await axios.post(
'http://localhost:8000/api/rest-auth/login/',
data
)
commit('ADD_USER', response.data)
this.$router.push('/')
} catch (error) {
return console.log(error)
}
},
}
export const getters = {
loggedIn(state) {
return !!state.credential
},
}
这里是 login.vue 代码
<template>
<client-only>
<div class="container">
<v-card max-width="500" class="margin-auto">
<v-card-title>Sign up</v-card-title>
<v-card-text>
<v-form @submit.prevent="submitUser">
<v-text-field
v-model="data.username"
label="Username"
hide-details="auto"
append-icon="account_circle"
></v-text-field>
<v-text-field
v-model="data.password"
label="Password"
hide-details="auto"
type="password"
append-icon="visibility_off"
></v-text-field>
<v-card-actions>
<v-btn color="success" type="submit" class="mt-4" dark>
Signup
</v-btn>
</v-card-actions>
</v-form>
<p>
Don't have an account? <nuxt-link to="/signup">Register</nuxt-link>
</p>
</v-card-text>
</v-card>
</div>
</client-only>
</template>
<script>
export default {
data() {
return {
data: {
username: '',
password: '',
},
}
},
methods: {
submitUser() {
this.$store.dispatch('signup/addUserLogin', this.data)
},
},
}
</script>
<style lang="scss" scoped>
.margin-auto {
margin: 2rem auto;
}
</style>
【问题讨论】:
-
我建议您使用 nuxt auth 包进行身份验证,请查看一次:auth.nuxtjs.org。
-
如果页面被刷新,您的商店将如何包含任何数据?您是否使用本地存储来存储用户的先前状态?理想情况下,您提到的情况并非如此,我们也可以在中间件中访问存储。请查看:nuxtjs.org/api/pages-middleware.
标签: javascript vue.js authorization vuex nuxt.js