Twelve: Basic use of routing, nested routing, query parameters, named routing, params parameters, routing props configuration, router-link’s replace attribute

1. Introduction to routing

1.1.What is routing

key + value = routing, routing is the corresponding relationship between a set of keys and values; a router manages multiple routes;

vue-router is a plug-in library for Vue, specially used to implement SPA applications;

1.2.Routing classification

(1) Front-end routing

1. The key is the path, and the value is the component, which is used to display the page content.
2. Working process: When the browser’s path changes, the corresponding component will be displayed.

(2) Backend routing

1. The key is the path, and the value is the function, which is used to process the request submitted by the client. (node.js)
2. Working process: When the server receives a request, it finds the matching function according to the request path to process the request and returns the response data.

1.3. Understanding of SPA applications

1. Single page web application (SPA).
2. The entire application has only one complete page index.html.
3. Clicking the navigation link in the page will not refresh the page, but will only partially update the page.
4. Data needs to be obtained through ajax request.

2. Basic use of routing

First you need to install vue-router:

Vue2 installs vue-router, command: npm i vue-router@3
Vue3 installs vue-router, command: npm i vue-router

2.1. Create components

Create About component and home component:

About.vue:

<template>
  <h2>I am the content of About</h2>
</template>

<script>
export default {
  name: "About",
};
</script>

<style>
</style>

Home.vue:

<template>
  <h2>I am the content of Home</h2>
</template>

<script>
export default {
  name: "Home",
};
</script>

<style>
</style>

2.2 Create router

Create router/index.js: routes in the configuration item refer to each route managed by the router;

// This file is used to create the router for the entire application
import VueRouter from 'vue-router'
//Introduce components
import About from '../components/About'
import Home from '../components/Home'

//Create and expose router
export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component:Home
        },
    ]
})

2.3 introduces the use of routers

Introduce and use the router plug-in in main.js:

import Vue from 'vue'
import App from './App.vue'

//Introduce routing VueRouter
import VueRouter from 'vue-router'
//Introduce router
import router from './router'

Vue.config.productionTip = false

//Use VueRouter plug-in
Vue.use(VueRouter)

newVue({
    el: '#app',
    render: h => h(App),
    router: router
})

2.4 Use routing plug-in to implement routing switching:

Use the tag to switch routes. to="/xxx" is the path displayed in the URL bar. active -class is the effect that can be displayed when you click this (highlight style)

 <!-- The original html uses the a tag to jump to the page -->
 <!-- <a class="list-group-item active" href="./about.html">About</a> -->
 <!-- <a class="list-group-item" href="./home.html">Home</a> -->

  <!-- Route switching is implemented in Vue with the help of the router-link tag -->
  <!-- active-class="active" indicates the style when the element is activated -->
 <router-link class="list-group-item" active-class="active" to="about">About</router-link>
 <router-link class="list-group-item" active-class="active" to="home" >Home</router-link>

2.5 Specify component rendering

To render component content on the page in App:

 <!-- Specify the component rendering position -->
            <router-view></router-view>

Points to note when using 2.6 routing

1. Routing components are usually stored in the src/pages folder, and general components are usually stored in the src/components folder. Generally, components are used as we used them before. For routing components, the tag is used to associate the routing rules configured in index.js, and then Place it in the specified location.

2. By switching, the “hidden” routing components are destroyed by default and can be mounted again when needed. So when switching, the routing component is always other destruction – current mount => other destruction – current mount =>. … …

3. Each component has its own $route attribute, which stores its own routing information.
4. Each component has a common router, which can be obtained through the $router attribute of the component.

3. Nested (multi-level) routing

3.1. Create News and Message components

News.vue:

<template>
  <ul>
    <li>news001</li>
    <li>news002</li>
    <li>news003</li>
  </ul>
</template>

<script>
export default {
  name: "News",
};
</script>

Message.vue:

<template>
  <div>
    <ul>
      <li><a href="/message1">message001</a> & amp;nbsp; & amp;nbsp;</li>
      <li><a href="/message2">message002</a> & amp;nbsp; & amp;nbsp;</li>
      <li><a href="/message/3">message003</a> & amp;nbsp; & amp;nbsp;</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Message",
};
</script>

3.2 Create sub-routes

Child routes are created through children. Note: secondary routes do not include slashes. Introduce Message and Home at the same time

......
import News from "../pages/News"
import Message from "../pages/Message"
//Create and expose router
export default new VueRouter({

    routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component:Home,
            // Sub-route, [] means there may be n more than one sub-route
            children: [
                {
                    path: 'news', //Secondary routing without slash...
                    component: News
                },
                {
                    path: 'message',
                    component: Message
                }
            ]
        },
    ]

3.3 Routing jump usage

Since it is nested within the Home component, you need to use in Home.vue to implement route jump and display it by

 <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link
            class="list-group-item"
            active-class="active"
            to="/home/news" //Write the complete path here, plus /
            >News</router-link>
        </li>
        <li>
          <router-link
            class="list-group-item"
            active-class="active"
            to="/home/message"
            >Message</router-link>
        </li>
      </ul>
      <!-- Click on who the router detects and displays -->
      <router-view></router-view>

4. Routing query parameters

To display the specific information of the message, you can use query to pass parameters. The query parameter is the configuration information in the component’s $route, which can be used to receive and transmit data. Similarly, there is the params parameter

4.1 Add Detail component

Add the detail component to display specific data:

<template>
  <ul>
    <li>Message number: {<!-- -->{ $route.query.id }}</li>
    <li>Message title: {<!-- -->{ $route.query.title }}</li>
  </ul>
</template>

<script>
export default {
  name: "Detail",
  mounted() {
    // Get component-related configuration information query
    console.log(this.$route);
  },
};
</script>

4.2 Configuring Level 3 Routing

First, configure the third-level routing in the message in the home in index.js

 routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,
            // Sub-route, [] means there may be n more than one sub-route
            children: [
                {
                    path: 'news',
                    component: News
                },
                {
                    path: 'message',
                    component: Message,
                    children: [
                        {
                            path: 'detail', //Level 3 routing
                            component:Detail,
                        }
                    ]

                }
            ]
        },
    ]

4.3 Routing jump parameters

There are two methods for routing jump parameters:

(1) The jump route carries the query parameter, the string writing method of to;

Use string concatenation (backticks) or template string in :to, write it directly after the routing path you want to go to, use ? connection, & amp; concatenation

(2) The jump route carries query parameters, and the object writing method of to (recommended)

Use object form to pass parameters in :to

<template>
  <div>
    <ul>
      <li v-for="m in messageList" :key="m.id">
        <!-- The jump route carries the query parameter, the string writing method of to -->
        <!-- <router-link :to="`/home/message/detail?id=${m.id} & amp;title=${m.title}`">
        {<!-- -->{m.title}}</router-link> -->

        <!-- The jump route carries the query parameter, the object writing method of to -->
        <router-link :to="{
            path: '/home/message/detail',
            query: { id: m.id,title: m.title,},
          }">
            {<!-- -->{ m.title }}</router-link>
      </li>
    </ul>
    <hr />
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Message",
  data() {
    return {
      messageList: [
        { id: "001", title: "Message 001" },
        { id: "002", title: "Message 002" },
        { id: "003", title: "Message 003" },
      ],
    };
  },
};
</script>

4.4 component receives data

$route of the target component receives the data. query, so data can be received through $route.query.id and $route.query.title

 <li>Message number: {<!-- -->{ $route.query.id }}</li>
    <li>Message title: {<!-- -->{ $route.query.title }}</li>

5. Named routing

Function: Simplify routing jumps

how to use:

First name the route with name: Name the route with name in the index routing configuration:

Usage: Change the traditional to:”/about” to :to=”{ name: ‘guanyu’ }”

 <router-link
            class="list-group-item"
            active-class="active"
            :to="{ name: 'guanyu' }"
            >About</router-link>

Note: This naming method cannot be used when using the string method when passing parameters in route jump

6. Routing params parameters

As can be seen from the picture, there are also params in $router, so parameters can also be passed through params.

6.1params passing parameters

Method (1): string writing method of to

 <!-- The jump route carries params parameters, the string writing method of to -->
       <router-link :to="`/home/message/detail/${m.id}/${m.title}`">
          {<!-- -->{ m.title }}</router-link> 

Method (2): object writing method of to

Note: When using params to pass parameters, you cannot use the path path, you must use the name configuration.

 <!-- When using the params parameter, you cannot use path: '/home/message/detail', you must use name configuration -->
<router-link
          :to="{
            name: 'xiangqin',
            params: { id: m.id, title: m.title},
          }">
          {<!-- -->{ m.title }}</router-link>

6.2 Declaring placeholders

Note: The name of the placeholder must be consistent with the attribute name of the passed params parameter, otherwise the URL will not be displayed.

 children: [
                        {
                            name: 'xiangqin',
                            // Use placeholders to indicate using params to pass parameters
                            path: 'detail/:id/:title',
                            component: Detail,
                        }
                    ]

6.3 Receiving parameters

Receive parameters within the component:

<ul>
    <li>Message number: {<!-- -->{ $route.params.id }}</li>
    <li>Message title: {<!-- -->{ $route.params.title }}</li>
  </ul>

7. Routing props configuration

When too many parameters are passed, a lot of the same content has to be written when receiving parameters, which is inconvenient and looks bloated.

The props configuration of the component is used to receive external incoming data;

The routing props configuration makes it easier for the routing component to receive parameters, without having to write long ones like $route.query/params.id.

7.1 First way of writing

The value is an object, and all key-values in the object are passed to the Detail component in the form of props.

This method passes fixed data and is not recommended.

 // The first way to write props: the value is an object, and all key-values in the object are passed to the Detail component in the form of props
  // The dead data passed is less used.
        props: { a: 1, b: 'hello' }

Component receives data:

<li>a:{<!-- -->{ a }}</li>
 <li>b:{<!-- -->{ b }}</li>
,,,,,,,
 props: ["a", "b"],

7.2 The second way of writing

The value is a Boolean value. If the Boolean value is true, all params parameters received by the routing component will be passed in the form of props.

This method is only suitable for passing parameters with params, not for query parameters. At this time, the message component cannot use query parameters to pass information to the detail component.

//The second way to write props: the value is a Boolean value. If the Boolean value is true, all params parameters received by the routing component will be passed to the Detail component in the form of props.
    props: true

7.3 The third way of writing

The props value is a function. Each set of key-value in the object returned by the function will be passed to the Detail component through props. This is the most commonly used. The function will receive parameters. This parameter is the $route, we can use it to get the content in query or params, and then pass it over

 // The third way to write props: the value is a function, and the key-value returned by the function is passed to the Detail component in the form of props
     props($route) {
            return { id: $route.query.id, title: $route.query.title }
            , } */
     //The third way to write destructuring assignment
        props({ query }) {
              return { id: query.id, title: query.title }
        }

Receive data

 props: ["id", "title"],

replace attribute of eight.router-link

Function: Control the mode of operating browser history when routing jumps

There are two ways to write browser history: push and replace. Push is to append the history record, and replace is to replace the current record. When routing jumps, defaults to push

How to enable replace mode: News

 //Write all
<router-link
            :replace="true"
            class="list-group-item"
            active-class="active"
            :to="{ name: 'guanyu' }"
            >About</router-link
          >
//abbreviation
          <router-link
            replace
            class="list-group-item"
            active-class="active"
            to="/home"
            >Home</router-link
          >

Use push to jump back, and use replace to directly replace and destroy the first one.

syntaxbug.com © 2021 All Rights Reserved.