Introduction
Implementing user authentication in Vue.js often includes the need for a user logout functionality. Logging out a user ensures that their session is terminated and they are no longer authenticated. In this guide, we'll explore how to create a user logout feature in a Vue.js application and provide sample code to demonstrate the process.
Sample Code
Let's create a Vue.js application with user logout functionality:
<div id="app">
<div v-if="authenticated">
<p>Welcome, {{ username }}!</p>
<button @click="logout">Logout</button>
</div>
<div v-else>
<p>Please log in to continue.</p>
<button @click="login">Login</button>
</div>
el: '#app',
data: {
authenticated: false,
username: null
},
methods: {
login() {
// Simulate a login action (e.g., with an authentication token)
// In a real application, you would implement proper authentication logic here
this.authenticated = true;
this.username = 'John Doe';
},
logout() {
// Log out the user
this.authenticated = false;
this.username = null;
}
}
});
In this code:
- We create a Vue component that displays different content based on the user's authentication status.
- When the user is authenticated, their username is shown, and a "Logout" button is available.
- If the user is not authenticated, a "Login" button is displayed, allowing them to log in.
- We use the `login` method to simulate a login action, setting the `authenticated` status and displaying the username.
- The `logout` method is used to log out the user, resetting the `authenticated` status and clearing the username.