#12 Part-3: Redirect User on the Dashboard and Access the Authenticated Route in Vue.js
In this tutorial, we will learn how to redirect the user to the dashboard after successfully logging in and how to access authenticated routes in a Vue.js application.
Step 1: Redirect User on the Dashboard
After a user successfully logs in, we want to redirect them to the dashboard page. We can do this by using the $router.push()
method provided by Vue Router. Here’s how you can implement this:
// In your login component
methods: {
loginUser() {
// Logic to authenticate user
// If user is authenticated
this.$router.push('/dashboard');
}
}
Step 2: Access Authenticated Route
To protect certain routes and only allow authenticated users to access them, we can use navigation guards provided by Vue Router. Here’s an example of how you can implement an authenticated route in Vue.js:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated()) {
next({
path: '/login',
query: { redirect: to.fullPath } // Save the target URL
})
} else {
next()
}
} else {
next()
}
})
function isAuthenticated() {
// Check if user is authenticated
}
export default router
With these steps, you can redirect the user to the dashboard after logging in and restrict access to certain routes to only authenticated users in your Vue.js application.