Intermediate
How can you implement routing in a Vue.js application?
Routing in Vue.js is handled using the Vue Router, which enables navigation between different components. This allows for a single-page application (SPA) experience where users can navigate without refreshing the browser.
To set up routing, you first need to install the Vue Router:
npm install vue-router
After installation, you can create a router instance and define routes:
import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
Vue.use(Router);
export default new Router({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
});
Finally, include the router in your main Vue instance:
new Vue({
el: '#app',
router,
render: h => h(App)
});
This setup allows users to navigate to the Home and About pages by changing the URL without reloading the page.