Detailed explanation of the installation and use of Vue-Router

Detailed explanation of the installation and use of Vue-Router

Install

1. Manually install vue-router in an existing Vue project

npm install --save vue-router

2. Use vue-cli to create a new project with vue-router Space selection/cancel a Select all i Invert

vue create project_name
#Vue will ask you which configuration to useDefault ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
Manually select features 

#Please select Manually select features, Vue will ask you what configurations the current project needs. Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)

>(*) Choose Vue version
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
( ) Router
( ) Vuex
( ) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing   
#Please select Router, and then choose the following series of questions according to the actual situation.

Basic configuration of routing

  1. If you choose the first installation method (manual installation), you need to manually create a folder named router under the src folder and create a new index.js file
  2. If you choose the second installation method (custom installation), you don't need to configure it yourself, you can use it directly after the new project is completed.

Installing Router in Vue

If you need the current Vue instance to support routing functions, you need to inject the VueRouter instance object into the Vue instance configuration option router when Vue is instantiated. (Manual installation)

// src/router/index.js

import Vue from 'vue' // Import Vue
import VueRouter from 'vue-router' // Import VueRouter

// Vue supports VueRouter
Vue.use(VueRouter)

let router = new VueRouter() // Initialize VueRouter

new Vue({  
  router // Configure the VueRouter instance object to the router option of the Vue instantiation configuration object}).$mount('#app')

Reference in main.js

// src/main.js

import router from './router'

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

Router configuration

Property name type describe
routes Array All routing configurations in the current Router
modeString Possible values: "hash" / "history" The default value is 'hash'. In this mode, the route uses hash to ensure that the route is consistent with the view. The history mode uses h5 to add window.history to achieve consistency between the route and the view.
linkActiveClass String Default value: "router-link-active" Global configuration Default activated class
linkExactActiveClass String Default value: "router-link-exact-active" Global configuration The default precise activation class.

Note that the to route path of a strictly matched link tag must be exactly equal to the current browser's URL, and the non-strictly matched current browser URL can be a sub-route of the current link.

example

to="/home" url="/home/user" non-strict match to="/home" url="/home/user/10086" non-strict match to="/home" url="/home" strict match to="/" url="/order" / is the root route of all routes, so they are non-strict matches

Router.routes configuration

{
  path: string,
  component?: Component, // The route component displayed when the current route matches name?: string, // Named route redirect?: string | Location | Function, // Route redirect props?: boolean | Object | Function, // 
  alias?: string | Array<string>, // Route alias children?: Array<RouteConfig>, // Nested routes beforeEnter?: (to: Route, from: Route, next: Function) => void, // Route guard caseSensitive?: boolean, // Is the matching rule case sensitive? (Default value: false)
}

Implementing a simple route

1. Configure routing

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import Home from './views/Home'
import Order from './views/Order'
import User from './views/User'

// Vue supports VueRouter
Vue.use(VueRouter)

let router = new VueRouter({
  routes: [
    {
      path: '/home',
      component: Home
    },
    {
      path: '/order',
      component: Order
    },
    {
      path: '/user',
      component: User
    }
  ]
})

new Vue({
  render: h => h(App),
  router
}).$mount('#app')       

2. Implement routing in components

VueRouter provides two components for Vue

  • router-link
  • router-view

1. router-link is used to implement the jump component of routing: the properties supported by this component

to: string | location When the user clicks this component, it will jump to the route specified by to

// Navigate to the specified URL
<router-link to="/home">Home</router-link>
<router-link to="/order">Order</router-link>
<router-link to="/user">user</router-link>
/* Navigate to the specified location
Common properties of location object in vue router {
    path:'/', //Specify the path of the jump route hash:'#top' //Specify the hash value of the jump route name: 'Home', //Specify the name value of the named route for the jump params: {}, //Specify the params object passed by the jump route query: {} //Specify the query key-value pair passed by the jump route }
*/
<router-link :to="{path:'/user'}">user</router-link>
// When using location to redirect a page, the params attribute of the current location cannot be passed to the routing component <router-link :to="{path:'/user',hash:'#top',params:{id:1,name:'Xiao Ming'}}">user</router-link>
// Using name route navigation, you can pass params to any named route
<router-link :to="{name:'User',hash:'#top',params:{id:1,name:'Xiao Ming'}}">user</router-link>
// query supports name navigation and path navigation. It is not recommended to use query to pass object attributes <router-link :to="{name:'User',hash:'#top',query:{id:1,name:'Xiao Ming'}}">user</router-link>

replace: bool When this property is true, the route jump will jump to the next page in the form of replacement (the next route will replace the url in the current browser history stack with the route to be jumped), the default value is false

// Use replacement to jump to the route <router-link class="tab-item" replace to="/user">user</router-link>

append: bool When this property is true, if the current route is a relative path (the path does not start with /), the route jump will be based on the browser URL to the next level. The default value is false

// If the current browser url is /order
// Clicking Gec will jump to /order/gec
<router-link to="gec" append>Gec</router-link>
// Click Gec1. Because the to of Gec1 is not a relative path, append will be invalid and the route will jump to /gec
<router-link to="/gec" append>Gec1</router-link>
// Clicking Gec2 without append will jump to /gec
<router-link to="gec">Gec2</router-link>

tag: string specifies what DOM element the router-link tag will be rendered to the page as. The default value is a

// Render router-link as a span element on the page <router-link tag="span" class="tab-item" to="/">Home</router-link>

active-class: string specifies the class name of the current router-link element if it does not strictly match the browser URL. The default value is the linkActiveClass value specified when VueRouter is instantiated

// The class name of the current router-link is aaaa when it is not strictly matched
<router-link active-class="aaaa" to="/order">Order</router-link>

event: string | Array<string> Specifies the current router-link element and declares events that can be used to trigger navigation. Can be a string or an array containing strings. The default value is click

//Both double-clicking and clicking can trigger the current element's route jump <router-link :event="['dblclick','click']" to="/">Home page</router-link>

2. router-view renders the corresponding routing view component when the routing path changes according to the current VueRouter configuration

The router-view component is a functional component that renders the view component that matches the path. The rendered component can also embed its own router-view and render nested components according to the nested path. All other attributes (except name, which are not used by router-view) are passed directly to the rendered component. In many cases, the data for each route is contained in the route parameters.

Because it is also a component, it can be used with transition and keep-alive. If you use both together, make sure to use keep-alive in the inner layer:

<transition name="fade">
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</transition>

The above is a detailed explanation of the installation and use of Vue-Router. For more information on the installation and use of Vue-Router, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of vue-router 4 usage examples
  • Detailed explanation of the use of router-view components in Vue
  • A simple example of using Vue3 routing VueRouter4
  • Complete steps to use vue-router in vue3
  • How to use Vue-router routing
  • Do you know how to use Router in vue3.0?

<<:  Docker installs and runs the rabbitmq example code

>>:  Detailed explanation of direct routing in cross-host communication of Docker containers

Recommend

MySQL Order By Multi-Field Sorting Rules Code Example

Say it in advance On a whim, I want to know what ...

CSS sets Overflow to hide the scroll bar while allowing scrolling

CSS sets Overflow to hide the scroll bar while al...

Solve the problem that PhpStorm fails to connect to VirtualBox

Problem description: When phpstorm's SFTP hos...

HTML page adaptive width table

In the pages of WEB applications, tables are ofte...

How to compile and install xdebug in Ubuntu environment

This article describes how to compile and install...

The whole process of realizing website internationalization using Vite2 and Vue3

Table of contents Preface Install vue-i18n Config...

Example code for implementing an Upload component using Vue3

Table of contents General upload component develo...

Basic usage and examples of yum (recommended)

yum command Yum (full name Yellow dog Updater, Mo...

Javascript design pattern prototype mode details

Table of contents 1. Prototype mode Example 1 Exa...

6 solutions for network failure in Docker container

6 solutions for network failure in Docker contain...

Summary of MySQL log related knowledge

Table of contents SQL execution order bin log Wha...

Vue codemirror realizes the effect of online code compiler

Preface If we want to achieve the effect of onlin...

WeChat applet implements waterfall flow paging scrolling loading

This article shares the specific code for WeChat ...

A permanent solution to MYSQL's inability to recognize Chinese

In most cases, MySQL does not support Chinese whe...

Detailed explanation of 8 ways to pass parameters in Vue routing components

When we develop a single-page application, someti...