1. Introduction and basic usage of vUE routes

1.1 What is Routing

A route is a mapping relationship

What are the routes in Vue?

  • Mapping between paths and components

1.2 Why Are Routes Used

Single page application (SPA): All functionality is implemented on a single HTML page

Front-end routing: Switches service scenarios

Advantages:

  • The whole page is not refreshed, and the user experience is better
  • Easy data transfer, high development efficiency

Disadvantages. 4:

  • High development costs (need to learn expertise)
  • The first load will be a little slower. Is not conducive to seo

1.3. The vue – the router is introduced

Vue – the router module package

It is deeply integrated with vue.js

Can define – View chart (mapping rule)

modular

Provides two built-in global components

Declarative navigation automatically activates links to CSS classes

1.4 the vue – the router to use

  1. The installation
yarn add vue-router
Copy the code
  1. Import the routing
import VueRouter from 'vue-router'
Copy the code
  1. Using routing plug-ins
// In vue, to use a plug-in that uses vue, call vue.use ().
Vue.use(VueRouter)
Copy the code
  1. Create an array of routing rules
const routes = [
  {
    path: "/find".component: Find
  },
  {
    path: "/my".component: My
  },
  {
    path: "/part".component: Part
  }
]
Copy the code
  1. Create route objects – incoming rules
const router = new VueRouter({
  routes
})
Copy the code
  1. Associated with a VUE instance
new Vue({
  router
})
Copy the code
  1. The components into the router – the view
<router-view></router-view>
Copy the code

2. Routing-declarative navigation

2.1 Declarative navigation – Basic use

  1. Vue-router provides a global component, router-link
  2. Router-link essentially ends up rendering a link to the to property which is equivalent to providing the href property (to without #)
  3. Router-link provides declarative navigation highlighting (built-in class name)
<template> <div> <div class="footer_wrap"> <router-link to="/find"> Find music </router-link> <router-link To ="/my"> </router-link> </router-link to="/part"> friend </router-link> </div> <div class="top"> </ router-view></router -view> </div> </div> </template>Copy the code

2.2 Declarative navigation – Skip passarguments

The value of the to attribute on the router-link is passed in the following syntax format

  • /path? Parameter name = Value
  • /path/ value – The route object needs to be configured in advance: /path/ Parameter name

The corresponding page component receives the value as passed

  • $route. The query. The parameter name
  • $route. Params. Parameter name
  1. Create components/ part. vue – Prepare to receive the parameters and values passed on the route
< the template > < div > < p > star watchers < / p > < p > find fascinating < / p > < p > look for partners < / p > < p > join us < / p > < p > names: {{ $route.query.name }} -- {{ $route.params.username }}</p> </div> </template>Copy the code
  1. Route definition
{
    path: "/part".component: Part
  },
  {
    path: "/part/:username".// A path with: indicates the value to be received
    component: Part
  },
Copy the code
  1. Navigation jump, pass value to MyGoods. Vue component
<router-link to="/part? </router-link> <router-link to="/part/ small "> </router-link>Copy the code

3. Routing – Redirection and mode

3.1 the redirection

  1. The default hash value of the url for opening a web page is /
  2. Redirect is to set the routing path to be redirected to
const routes = [
  {
    path: "/".// Default hash value path
    redirect: "/find" // Redirect to /find
    // The path after # in the browser URL is changed to /find- to rematch the array rule}]Copy the code

3.2 404 page

Paths do not match. The corresponding component page is displayed

1. Create a page

<template> <img src=".. /assets/404.png" alt=""> </template>Copy the code

2. Modify route configurations

import NotFound from '@/views/NotFound'

const routes = [
  / /... Other configurations are omitted
  // 404 at the end (the rule is to compare path from front to back)
  {
    path: "*".component: NotFound
  }
]
Copy the code

3.3 Mode Setting

 const router = new VueRouter({  routes,  mode: "history" // The mode is hash})
Copy the code

4. Programmatic navigation

4.1 Program navigation – Basic use

Grammar:

this.$router.push({
    path: "Routing path".// Go to router/index.js definition
    name: "Route name"
})
Copy the code
  1. Main.js – Route array, give the route a name
{
    path: "/find",
    name: "Find",
    component: Find
},
{
    path: "/my",
    name: "My",
    component: My
},
{
    path: "/part",
    name: "Part",
    component: Part
},
Copy the code
  1. App.vue – Replace span with js programmatic navigation jump
< the template > < div > < div class = "footer_wrap" > < span @ click = "BTN ('/find ', 'find')" > find music < / span > < span @ click = "BTN ('/my ' "> <span style =" box-sizing: border-box! Important; word-wrap: break-word! Important; Friends' Part ') "> < / span > < / div > < div class =" top "> < the router - the view > < / router - the view > < / div > < / div > < / template >Copy the code

4.2 Programmatic navigation – Jump pass parameters

Syntax Select query/params

this.$router.push({
    path: "Routing path"
    name: "Route name".query: {
    	"Parameter name": value}params: {
		"Parameter name": value}})// The corresponding route receives $route.params. parameter name Value
// The corresponding route receives $rout.query. Parameter name Value
Copy the code

Note: Using path will automatically ignore params==

1.App.vue

< the template > < div > < div class = "footer_wrap" > < span @ click = "BTN ('/find ', 'find')" > find music < / span > < span @ click = "BTN ('/my ' 'My') "> My music < / span > < span @ click =" oneBtn "> friends - bio < / span > < span @ click =" twoBtn "> friends - little wisdom < / span > < / div > < div class =" top "> </div> </div> </template>.<script> // target: program navigation - jump route parameters // params => $route. Parameter name // Method 2: // query => $route. Parameter name // Important: path is automatically ignored params // Recommend: name+query // Note: If the current URL "hash value and? The parameter "and the hash value to which you're jumping? Export default {methods: {BTN (targetPath, targetName){ $router.push({// path: targetPath, name: targetName})}, oneBtn(){this.$router.push({// path: targetPath, name: targetName})}, oneBtn(){this.$router-. 'Part, params: {the username:' bio '}})}, twoBtn () {this. $router. Push ({name: 'Part, query: {name: "little wisdom"}})}}}; </script>Copy the code

5. Routing – Nesting and guarding

** Route guard :** routes will execute beforeEach function once before they actually jump, and next call will jump, or you can force to change the route to jump

5.1 Route Nesting

  1. How to configure the level-2 route?

  2. Create the required secondary page components

  3. The children of the routing rule is configured with a secondary routing rule object

  4. Set router-view on the Level 1 page to display the level 2 route page

  5. What should I pay attention to in secondary routing?

  6. The secondary route path is not the root path /

  7. When jumping, the path must start with /

  8. Specific operations:

  9. Secondary navigation and styling

<template> <div> <div class="nav_main"> <router-link to="/find/recommend"> </router-link> <router-link To ="/find/ranking"> </router-link> </router-link> <div style="1px solid red;" > <router-view></router-view> </div> </div> </template>Copy the code
  1. Routing Rules – Displays level-2 routes
const routes = [
  / /... Omit the other
  {
    path: "/find".name: "Find".component: Find,
    children: [{path: "recommend".component: Recommend
      },
      {
        path: "ranking".component: Ranking
      },
      {
        path: "songlist".component: SongList
      }
    ]
  }
  / /... Omit the other
]
Copy the code

5.2 Declaring navigation-class Name Differences

  • Router-link-exact -active Indicates the hash value path in the URL, which is the same as the href value. Set this parameter to this type
  • Router-link-active (fuzzy matching) Hash value in the URL, including the href value of the path

5.3 Navigation Guard

** Function: ** is triggered every time a route hop is routed. It can be used to intercept or release a route hop.

** Scenario: ** Login status interception. For example, the specified page cannot be accessed without login.

Usage:

Call the beforEach method on the Router object to bind the navigation guard

// Target: route guard
// Scenario: when you want to determine the route permission
// Syntax: router.beforeeach ((to, from, next)=>{// Route forward "before" execute here to determine whether to forward})
// Parameter 1: the destination of the route (route object information) to jump to
// Parameter 2: Where does the route (route object information) come from
// Argument 3: the body of the function -next () will give way to the normal jump switch, next(false) will stay in place, next(" force change to another routing path ")
// Note: If you don't call next, the page stays where it is

// Example: determine if the user is logged in, decide whether to go to "my music "/my
const isLogin = true; // Login status (not logged in)
router.beforeEach((to, from, next) = > {
  if (to.path === "/my" && isLogin === false) {
    alert("Please log in")
    next(false) // Block route hops
  } else {
    next() // Release normally}})Copy the code

6. Vant component library

6.1 vant component library

Features:

  • Provides more than 60 high-quality components, covering a variety of mobile scenarios
  • Excellent performance, the average component size is less than 1KB
  • Complete documentation and examples in Both English and Chinese
  • Vue 2 and Vue 3 are supported
  • Support for on-demand import and theme customization

6.2 Importing All

  1. Download the Vant component library into the current project
yarn add vant -D
Copy the code
  1. Import all components, in main.js
import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';

Vue.use(Vant);
Copy the code
  1. Using button components
<van-button type="primary"> Main button </van-button> <van-button type="info"> Information button </van-button> <van-button Type ="default"> Default button </van-button> <van-button type="warning"> Warning button </van-button> <van-button Type ="danger"> </van-button>Copy the code

6.3 Manually Importing on Demand

1. Manually imported separately, quick start:

// Mode 2: Manually import on demand
// import Button from 'vant/lib/button'; / / button component
// import 'vant/lib/button/style'; / / button style
Copy the code
  1. registered
// components: {// manually register the component name
// // VanButton: Button
// // equivalent
// [Button.name]: Button
// }
Copy the code
  1. use
<van-button type="primary"> Main button </van-button> <van-button type="info"> Information button </van-button> <van-button Type ="default"> Default button </van-button> <van-button type="warning"> Warning button </van-button> <van-button Type ="danger"> </van-button>Copy the code

6.4 Automatic Import on demand

  1. Installing a plug-in
yarn add babel-plugin-import -D
Copy the code
  1. In the Babel configuration file (babel.config.js)
module.exports = {
  plugins: [['import', {
      libraryName: 'vant'.libraryDirectory: 'es'.style: true
    }, 'vant']]};Copy the code
  1. Global registration – will be automatically introduced on demand
// Mode 1: global - Automatically import Vant components on demand
// (1): download babel-plugin-import
// (2): babel.config.js - add the configuration mentioned in the official website (be sure to restart the server)
// (3): main.js import a component on demand, vue. use global registry - a.vue file to use the Vant component directly
import { Button } from 'vant';
Vue.use(Button) // Button component global registration, the real registered component name VanButton
Copy the code