Project Setup and Initialization
To implement client-side navigation, install the vue-router library (version 3.x). Begin by defining the router instance within src/router/index.js. Import necessary components and register the router plugin with Vue.
import Vue from 'vue';
import VueRouter from 'vue-router';
import HeaderView from '@/components/TopBar.vue';
import MainLayout from '@/components/MainArea.vue';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{ path: '/user/:uid', name: 'ProfilePage', component: HeaderView },
{ path: '/dashboard', component: MainLayout }
]
});
export default router;
Next, instantiate the root application in main.js, linking the router configuration to ensure views update correctly upon URL changes.
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
router
}).$mount('#app');
Dynamic Route Parameters and Navigation
Routes can accept dynamic segments by prefixing them with a colon (e.g., :id). When navigating programmatically via JavaScript methods, utilize $router.push to move between views. This suppports both query strings and path parameters depending on your route definition.
methods: {
initiateNavigation () {
// Option A: Named route with query arguments
this.$router.push({
name: 'ProfilePage',
query: { userId: '554a1' }
});
// Option B: Direct path with params
// Ensure path in router is /user/:uid
this.$router.push(`/user/${userId}`);
}
}
Ensure that when using named routes, the name property matches the one defined in the route configuration array.
URL Modes and History Management
By default, Vue Router utilizes hash-based mode (# in URL). To remove the hash symbol and achieve cleaner URLs compatible with backend routing servers, configure the mode as history.
const router = new VueRouter({
mode: 'history',
routes: [...]
});
Navigating backward through the browser history stack is supported directly through instance methods:
<button @click="handleBack">Go Back</button>
<span @click="$router.back()">Previous Page</span>
<span @click="$router.go(-1)">Step Back</span>
Redirects and Error Handling
Automatically forward users from deprecated or root paths using the redirect property. For unmatched paths, define a catch-all route using a wildcard (*) at the end of the routes array to handle 404 scenarios gracefully.
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', redirect: '/dashboard' },
{ path: '/old-page', redirect: '/home' },
{ path: '*', component: NotFoundComponent }
]
});
Component Caching and Lifecycle Hooks
To preserve state when toggling between active tabs or views, wrap the <router-view> component inside <keep-alive>. Specify component names in the include attribute to select wich views should be cached.
When a component is included in the keep-alive cache, its lifecycle hooks differ slight from standard mounting. Instead of created or mounted running every time the view is shown, use activated and deactivated hooks to manage logic specific to the cached state transitions.
Authentication Guard Implementation
For protected pages requiring login, store the current location before forcing a redirect to the login screen. Upon successful authentication, check for this stored reference to return the user to their intended destination.
// Before navigating to login
this.$router.replace({
path: '/signin',
query: { backUrl: this.$route.fullPath }
});
// On Login Page after success
const destination = this.$route.query.backUrl || '/landing';
this.$router.replace(destination);
This approach ensures seamless user experience while maintaining security boundaries.