我想在我的应用程序中实现注销,所以我在 Nuxt 的文档logout()
中看到了功能,我不知道它是如何工作的,因为它没有在文档中解释,但我尝试使用它,但它对我不起作用,当我点击在链接上,用户保持身份验证,但只是重定向到主页。在我的服务器中我没有函数,我使用的是 laravel/passport,登录请求的响应是一个令牌和用户数据,然后我将它们保存在 vuex 中,如果我手动使用持久状态来避免清空状态刷新页面。logout
logout
Navbar.vue我使用注销
<template>
<li v-if="$auth.loggedIn" class="nav-item">
<nuxt-link class="nav-link" to="/" @click="logout">logout</nuxt-link>
</li>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser']),
},
methods: {
async logout() {
await this.$auth.logout()
},
},
}
</script>
存储/index.js
<script>
export const state = () => ({
user: {},
token: '',
id: '',
})
export const mutations = {
saveUser(state, payload) {
state.user = payload
},
saveId(state, id) {
localStorage.setItem('id', id)
state.id = id
},
saveToken(state, token) {
localStorage.setItem('authToken', token)
localStorage.getItem('authToken')
state.token = token
},
}
export const actions = {
saveUserAction({ commit }, UserObject) {
commit('saveUser')
},
logoutUser({ commit }) {
commit('logout_user')
},
}
export const getters = {
getUser: (state) => {
return state.user
},
isAuthenticated(state) {
return state.auth.loggedIn
},
loggedInUser(state) {
return state.user.user
},
}
</script>
登录.vue
<script>
export default {
methods: {
async login() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
this.$store.commit('saveUser', succesfulLogin.data.user)
this.$store.commit('saveToken', succesfulLogin.data.token)
this.$store.commit('saveId', succesfulLogin.data.user.id)
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
this.$router.push('/profile')
}
},
},
}
</script>