redirect to dashboard after login in vue
// Import the necessary modules
import Vue from 'vue';
import VueRouter from 'vue-router';
// Use VueRouter
Vue.use(VueRouter);
// Create a new VueRouter instance
const router = new VueRouter({
mode: 'history',
routes: [
// Define your routes here
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: {
// Add meta field to indicate that this route requires authentication
requiresAuth: true
}
},
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue')
}
]
});
// Add a global navigation guard to check for authentication before each route navigation
router.beforeEach((to, from, next) => {
// Check if the route requires authentication
if (to.matched.some(record => record.meta.requiresAuth)) {
// Check if the user is authenticated (you need to implement your own authentication logic)
if (!isAuthenticated()) {
// If not authenticated, redirect to the login page
next({ name: 'Login' });
} else {
// If authenticated, proceed with the navigation
next();
}
} else {
// If the route does not require authentication, proceed with the navigation
next();
}
});
// Function to check if the user is authenticated (replace this with your authentication logic)
function isAuthenticated() {
// Replace this with your own authentication logic
// For example, check if there is a token in localStorage
return localStorage.getItem('token') !== null;
}
// Export the router instance
export default router;
// In your Login.vue component, after a successful login, redirect to the dashboard
// Import Vue and the router
import Vue from 'vue';
import router from '@/router';
// Inside your login method or after a successful login response
// Redirect to the dashboard using the router
router.push({ name: 'Dashboard' });
Make sure to replace the placeholder components and authentication logic with your actual components and authentication implementation.