This is the 19th day of my participation in the More text Challenge. For details, see more text Challenge

introduce

The Vue Router is the official route manager of vue. js. Its deep integration with the vue.js core makes building a single page application a breeze.

The installation

1. Manually install the VUE-Router in an existing Vue project

npm install --save vue-router
Copy the code
  1. Use vue-cli to create a new project with vue-router

Space Select/Cancel a Select all I Deselect

Vue create project_name #Vue will ask you which configuration to use Default ([vue2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] Manually select features,Vue will ask you which configuration Check the features needed for your current projectforyour 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 Select, the next series of questions to select according to the actual situationCopy the code

Basic configuration of routes

  1. If you select the first installation mode (manual installation), manually create a folder named router under the SRC folder and create the index.js file

  2. If you choose the second installation mode (custom installation), you do not need to configure yourself, after the new project can be directly used

Install the Router into the Vue

If the current Vue instance needs to support routing. The VueRouter instance object needs to be injected into the Vue instance configuration option router when Vue is instantiated. (Manual installation)

// src/router/index.js

import Vue from 'vue' / / into the Vue
import VueRouter from 'vue-router' / / introduce VueRouter

// Vue supports VueRouter
Vue.use(VueRouter)

let router = new VueRouter() // Initialize VueRouter

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

In the main. Js references

// src/main.js

import router from './router'

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

Configure the Router

The property name type describe
routes Array All routes are configured on the current Router
modeString Optional values: “hash”/”history” Default value: ‘hash’ In this mode, hash is used to ensure that the route is consistent with the view. History In this mode, window.history is added in H5 to ensure that the route is consistent with the view
linkActiveClass String Default: “router-link-active” The default active class is configured globally
linkExactActiveClass String Default value: “router-link-exact-active” The global configuration defaults to precisely activated classes.

Notice The route path that strictly matches the link tag to must be equal to the url of the current browser. If not, it can be a child route of the current link.

example

to="/home"   url="/home/user"Not strictly matched to="/home"   url="/home/user/10086"Not strictly matched to="/home"   url="/home"Strictly match to="/"       url="/order"/ is the root of all routes, so they are not strictly matchedCopy the code

Route. routes configurations

{
  path: string, component? : Component,// The routing component displayed when the current route matchesname? : string,// Name the routeredirect? : string | Location |Function.// Route redirectionprops? : boolean |Object | Function.// alias? : string |Array<string>, // Route aliaschildren? :Array<RouteConfig>, // Set set bybeforeEnter? :(to: Route, from: Route, next: Function) = > void.// Route guardcaseSensitive? : boolean,// Is the matching rule case-sensitive? (Default: false)
}
Copy the code

Implement a simple route

1. Configure routes

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({
  renderh= > h(App),
  router
}).$mount('#app')       
Copy the code

2. Implement routing in components

VueRouter provides Vue with two components

  • router-link
  • router-view

1. Router-link Router-link component used to implement routing: properties supported by the component

To: string | location when the user clicks on the component will jump to the to the designated route

// Navigate to the specified URL
<router-link to="/home"> home page < / router - the link ><router-link to="/order">The order</router-link>
<router-link to="/user">The user</router-link>
{path:'/', // hash:'#top'; // Hash :'#top'; 'Home', // specifies the name value of the route to be passed params: {}, // specifies the route to be passed params object query: {} // Specifies the route to be passed query key-value pair} */
<router-link :to="{path:'/user'}">user</router-link>
// 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 the 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 both name and path navigation. It is not recommended to pass query when passing object attributes
<router-link :to="{name: 'User', hash: '# top, query: {id: 1, name:' xiao Ming '}}">user</router-link>
Copy the code

Replace: bool When this property is true, the route’s jump will jump to the next page as a replacement (the next route replaces the URL in the current browser history stack with the route to jump to). The default value is false

// Use the substitution form to skip the route
<router-link class="tab-item" replace to="/user"> user < / router - the link >Copy the code

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

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

Tag: string specifies what DOM element the router-link tag will eventually render to the page. The default value is a

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

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

// When the current router-link is not strictly matched, the class name is aaaa
<router-link  active-class="aaaa" to="/order"> order < / router - the link >Copy the code

Exact -active-class:string Specifies the class name of the current router-link element if it matches the url of the browser. The default value is the value specified by linkExactActiveClass when VueRouter is instantiated

// The class name of the current strictly matched router-link is ex
<router-link exact-active-class="ex" to="/"> home page < / router - the link >Copy the code

Exact: bool Specifies that the current router-link element is strictly matched. Active-class can be activated only in strict matching mode. The default value is false

// The strict matching mode is enabled for the current route
<router-link exact  to="/"> home page < / router - the link >Copy the code

Event: string | Array < string > specify the current router – the link element, the statement can be used to trigger a navigation event. It can be a string or an array of strings. The default is click

// Both a double click and a click can trigger a route jump for the current element
<router-link :event="['dblclick','click']"  to="/"> home page < / router - the link >Copy the code

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

The router-View component is a functional component that matches the rendering path to the view component. The rendered component can also embed its own router-view, rendering the nested component based on the nested path. All other properties (except for the name used by non-router-views) are passed directly to the rendering component, and in many cases the data for each route is included in the route parameters.

<div id="app">
  <router-view data="somedata"/>
</div>
// The data property is passed as props to the view component rendered by the router-view
Copy the code

Since it is also a component, it can be used with transition and keep-alive. If the two are used together, be sure to use keep-alive on the inner layer:

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