Vue's Router is a plug-in for page jumping and routing management. It can help us load different components according to different URL requests and implement front-end routing functions. When using Vue's Router, it needs to be configured in basic configuration. The following are the basic Router configuration commands for Vue.
1. Install Vue Router
Use npm to install Vue Router, open the terminal and execute the following command in the project directory:
npm install vue-router
2. Import Vue Router
Import Vue Router in a file and register it as a plugin for Vue using the method:
import Vue from 'vue' import VueRouter from 'vue-router' (VueRouter)
3. Create a routing instance
Create a routing instance in the file and configure routing rules:
import Vue from 'vue' import VueRouter from 'vue-router' import Home from './components/' import About from './components/' (VueRouter) const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = new VueRouter({ mode: 'history', // Use HTML5's history mode to remove "#" in the URL routes })
4. Mount the routing instance
Mount the routing instance onto the Vue instance in the file:
new Vue({ router, render: h => h(App) }).$mount('#app')
5. Configure routing exit
In Vue's root component, the corresponding components of the route are displayed through tags:
<template> <div> <router-view></router-view> </div> </template>
Through the above configuration, we have completed the basic configuration of Vue's Router. Here is a complete example:
First, create two components in the src/components directory, and.
The content is as follows:
<template> <div> <h2>Welcome to Home Page</h2> </div> </template> <script> export default { name: 'Home' } </script>
The content is as follows:
<template> <div> <h2>Welcome to About Page</h2> </div> </template> <script> export default { name: 'About' } </script>
Then, create the file in the src/router directory, with the following content:
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '@/components/' import About from '@/components/' (VueRouter) const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = new VueRouter({ mode: 'history', routes }) export default router
Finally, perform the following configuration in the src/ file:
import Vue from 'vue' import App from './' import router from './router/index' new Vue({ router, render: h => h(App) }).$mount('#app')
The above are the basic configuration commands and code examples of Vue Router. Through these configurations, we can implement jump between pages and front-end routing functions.
This is the end of this article about the basic configuration command of Router in vue. For more related content of vue Router, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!