vue.jsHow do I set up routing in a Vue.js application?
Setting up routing in a Vue.js application requires the use of a routing library. The official library for routing in Vue.js is Vue Router.
To install Vue Router, you can use npm or yarn:
# npm
npm install vue-router
# yarn
yarn add vue-router
Once Vue Router is installed, you will need to set up the routes for your application. To do this, create a routes.js
file and define the routes you want to use:
import Home from './views/Home.vue'
import About from './views/About.vue'
export default [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
]
Then, in the main app.js
file, import the routes and use the Vue.use()
method to configure Vue Router:
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes.js'
Vue.use(VueRouter)
const router = new VueRouter({
routes
})
new Vue({
router
}).$mount('#app')
Finally, in the app.vue
file, use the <router-view>
component to render the routes:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
By following these steps, you can set up routing in a Vue.js application.
Code explanation
**
npm install vue-router
: Installs Vue Router using npm.yarn add vue-router
: Installs Vue Router using yarn.routes.js
: File containing the routes for the application.import routes from './routes.js'
: Imports the routes from theroutes.js
file.Vue.use(VueRouter)
: Configures Vue Router.const router = new VueRouter({ routes })
: Creates a newVueRouter
instance with the routes.<router-view>
: Component used to render the routes.
## Helpful links
More of Vue.js
- How to use a YAML editor with Vue.js?
- How do I use the v-if directive in Vue.js?
- How can I implement pinch zoom functionality in a Vue.js project?
- How do I unmount a Vue.js component?
- How can I use Vue.js to implement a zoomable image?
- How do I use Yup with Vue.js?
- How do I choose between Vue.js and Svelte for my software development project?
- How do I use a Vue.js QR code generator?
- How do I use the Vue.js playground to develop software?
- How can I measure the popularity of Vue.js?
See more codes...