keep-alive vuejs router
Step 1: Import the Vue and Vue Router libraries.
import Vue from 'vue';
import VueRouter from 'vue-router';
Step 2: Use VueRouter and Vue.use to enable routing in the Vue application.
Vue.use(VueRouter);
Step 3: Define the Vue components that will be used as pages in your application.
const Home = { template: '<div>Home Component</div>' };
const About = { template: '<div>About Component</div>' };
Step 4: Create a VueRouter instance and configure routes with components.
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
],
});
Step 5: In your main Vue instance, use the router and wrap the app with the router-view component.
const app = new Vue({
router,
template: '<router-view></router-view>',
}).$mount('#app');
Step 6: Integrate keep-alive in the router-view to cache components for improved performance.
const app = new Vue({
router,
template: '<router-view v-if="$route.meta.keepAlive"></router-view>',
}).$mount('#app');
Step 7: Add meta tags to your route configurations to indicate which components should be cached.
const router = new VueRouter({
routes: [
{ path: '/', component: Home, meta: { keepAlive: true } },
{ path: '/about', component: About, meta: { keepAlive: true } },
],
});
Step 8: Optionally, you can use the activated and deactivated lifecycle hooks in your components for custom logic when a component is cached or removed from the cache.
const Home = {
template: '<div>Home Component</div>',
activated() {
console.log('Home Component Activated');
},
deactivated() {
console.log('Home Component Deactivated');
},
};
Step 9: Customize the keep-alive behavior by using the include and exclude attributes to specify which components should be cached or ignored.
<keep-alive :include="['Home']">
<router-view></router-view>
</keep-alive>
Step 10: Implement navigation between routes using the router-link component.
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
Step 11: Run your Vue application and observe the caching behavior with keep-alive in action.