I want to implement logout in my app so I saw logout()
function in the documentation of Nuxt, I don't know how it exactly works since its not explained in the documentation but I tried to use it but its not working for me, when I click on logout
link the user stays authenticated but just redirected to home page.
in my server I don't have a logout
function, I'm using laravel/passport, the response of a login request is a token and user data which then I save them in vuex and I use persistedstate to avoid emptying the state if I manually refresh the page.
Navbar.vue where I use logout
<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>
store/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>
login.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>
thats how the store looks after I press on logout
, loggedIn
stays true
Did you tried this?
await this.$auth.logout()
Also, try to bind it to a button rather than a link.
I'm not sure that the @click
event happens properly when you have a nuxt-link
.