The basic concept and principle of routing, the basic use of Vue router, nested routing, dynamic routing matching, named routing, programmed navigation

1. Basic concept and principle of routing

1.1 routing

  • Routing is a broad and abstract concept. The essence of routing is a correspondence. For example, after we enter the url address we want to access in the url address, the browser needs to request the resource corresponding to the url address.
  • Then there is a corresponding relationship between the url address and the real resource, that is, routing.

In development, routing is divided into front-end routing and back-end routing.

(1) The back-end routing is implemented by the server and completes the distribution of resources.

  • Concept: return different contents according to different user URL requests.
  • Essence: the correspondence between the URL request address and the server resource.

(2) Front end routing depends on the change of hash value (anchor link).

  • Concept: display different page contents according to different user events.
  • Essence: the correspondence between user events and event handlers.
  • Front end routing is to display different page contents according to different events, that is, the corresponding relationship between events and event handling functions.
  • The main task of front-end routing is to listen to events and distribute and execute event handling functions.
  • The performance of back-end routing is lower than that of front-end routing. Therefore, we mainly study front-end routing next.

(3) SPA (Single Page Application)

  • Back end rendering (performance issues).
  • Ajax front-end rendering (front-end rendering improves performance, but does not support browser forward and backward operations).
  • SPA (Single Page Application) Single Page Application: there is only one page in the whole website. The change of content is realized through Ajax local update. At the same time, it supports the forward and backward operations of browser address bar.
  • One of the implementation principles of SPA: hash based on URL address (the change of hash will lead to the change of browser record access history, but the change of hash will not trigger a new URL request).
  • In the process of implementing SPA, the core technology point is front-end routing.

1.2 initial experience of front-end routing

  • Front end routing is implemented based on the change of hash value (for example, click the menu or button in the page to change the hash value of URL, and control the switching of components according to the change of hash value).
  • The core implementation relies on one event, that is, the event to listen for the change of hash value.
 // Listen to the onhashchange event of window and switch the name of the component to be displayed according to the latest hash value obtained
window.onhashchange = function () {
    // Get the latest hash value through location.hash
    console.log(location.hash);
}

Case: front end routing realizes tab bar switching

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Case: front end routing implementation tab Column switching</title>
    <!-- Import vue file -->
    <script src="./lib/vue_2.5.22.js"></script>
</head>

<body>
    <!-- cover vue Instance controlled div region -->
    <div id="app">
        <!-- Toggle component hyperlinks -->
        <a href="#/Zhuye "> Home Page</a>
        <a href="#/Keji "> Technology</a>
        <a href="#/Caijing "> Finance</a>
        <a href="#/Yule "> Entertainment</a>

        <!-- according to :is Property to specify the component name and render the corresponding component to component Location of the label -->
        <!-- Can put component The tag is used as a placeholder for the component -->
        <component :is="comName"></component>
    </div>

    <script>
        // #region defines the four components that need to be switched
        // Home page component
        const zhuye = {
            template: '<h1>Home page information</h1>'
        };

        // Technology components
        const keji = {
            template: '<h1>Scientific and technological information</h1>'
        };

        // Financial component
        const caijing = {
            template: '<h1>Financial information</h1>'
        };

        // Entertainment components
        const yule = {
            template: '<h1>Entertainment information</h1>'
        };
        // #endregion

        // #region vue instance object
        const vm = new Vue({
            el: '#app',
            data: {
                comName: 'zhuye'
            },
            // Register private components
            components: {
                zhuye,
                keji,
                caijing,
                yule
            }
        });
        // #endregion

        // Listen to the onhashchange event of window and switch the name of the component to be displayed according to the latest hash value obtained
        window.onhashchange = function () {
            // Get the latest hash value through location.hash
            console.log(location.hash);
            switch (location.hash) {
                case '#/zhuye':
                    vm.comName = 'zhuye';
                    break;
                case '#/keji':
                    vm.comName = 'keji';
                    break;
                case '#/caijing':
                    vm.comName = 'caijing';
                    break;
                case '#/yule':
                    vm.comName = 'yule';
                    break;
            }
        }
    </script>
</body>

</html>

Core idea:
There is a vue instance object in the page. There are four components in the vue instance object, which are the component content to be displayed in the tab bar switching. There are four hyperlinks in the page, as follows:

<a href="#/Zhuye "> Home Page</a> 
<a href="#/Keji "> Technology</a> 
<a href="#/Caijing "> Finance</a>
<a href="#/Yule "> Entertainment</a>

When we click these hyperlinks, the hash value in the url address will be changed. When the hash value is changed, the onhashchange event will be triggered. When the onhashchange event is triggered, we will display different components according to the hash value:

        // Listen to the onhashchange event of window and switch the name of the component to be displayed according to the latest hash value obtained
        window.onhashchange = function () {
            // Get the latest hash value through location.hash
            console.log(location.hash);
            switch (location.hash) {
                case '#/zhuye':
                    vm.comName = 'zhuye';
                    break;
                case '#/keji':
                    vm.comName = 'keji';
                    break;
                case '#/caijing':
                    vm.comName = 'caijing';
                    break;
                case '#/yule':
                    vm.comName = 'yule';
                    break;
            }
        }

2. Basic use of Vue router

2.1 introduction to Vue router

  • Vue Router (official website: https://router.vuejs.org/zh/ )It is the official route manager of Vue.js. It is a more powerful front-end router. It is recommended.
  • It is deeply integrated with the core of Vue.js and can be very convenient for the development of SPA(single page web application) applications.
  • Vue Router depends on Vue, so you need to import Vue first and then Vue Router.

Vue Router includes the following functions:

  • Support H5 history mode or hash mode
  • Support nested routing
  • Support routing parameters
  • Support programmatic routing
  • Support named routing
  • Support routing navigation guard
  • Support routing transition animation effects
  • Support lazy loading of routes
  • Support routing scrolling behavior

2.2 basic use of Vue router

2.2.1 basic use steps

  1. Import related library files
  2. Add routing link
  3. Add route padding bit
  4. Define routing components
  5. Configure routing rules and create routing instances
  6. Mount the route to the Vue root instance

1. Import related library files

<!-- Import vue File, global window Object mount Vue Constructor -->
<script src="./lib/vue_2.5.22.js"></script>
<!-- Import vue-router File, global window Object mount VueRouter Constructor -->
<script src="./lib/vue-router_3.0.2.js"></script>

2. Add routing link

<!-- router-link yes vue The labels provided in are rendered as by default a label -->
<!-- to Attributes are rendered as by default href attribute -->
<!-- to The value of the property is rendered as by default # Initial hash address -- >
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>

3. Add route fill bit

<!-- Route padding bit (also known as route placeholder) -->
<!-- In the future, the components matched by routing rules will be rendered to router-view Location -->
<router-view></router-view>

4. Define routing components

var User = {
	template: '<div>User</div>'
}
var Register = {
	template: '<div>Register</div>'
}

5. Configure routing rules and create routing instances

// 5. Configure routing rules and create routing instances
// Create routing instance object
const router = new VueRouter({
    // routes is an array of routing rules
    routes: [
        // Each routing rule is a configuration object, which contains at least two attributes: path and component:
        // path indicates the hash address matched by the current routing rule
        // Component indicates the component to be displayed corresponding to the current routing rule
        { path: '/user', component: User },
        { path: '/register', component: Register }
    ]
});

6. Mount the route to the Vue root instance

// 6. Mount the route to the Vue root instance
const vm = new Vue({
    // Specifies the area to control
    el: '#app',
    data: {},
    // Mount routing instance object
    // router: router
    router
});

2.2.2 route redirection

  • Routing redirection refers to forcing the user to jump to address C when accessing address A, so as to display A specific component page;
  • You can easily set the redirection of a route by specifying a new route address through the redirect attribute of the routing rule:
var router = new VueRouter({
	routes: [
		// Where, path represents the original address to be redirected, and redirect represents the new address to be redirected
		{path:'/', redirect: '/user'},
		{path:'/user',component: User},
		{path:'/register',component: Register}
	]
});

3. Usage of Vue router nested route

3.1 nested routing function analysis

  • Click the parent route link to display the template content
  • There are child routing links in the template content
  • Click the child routing link to display the child template content

3.2 parent routing component template

  • Parent routing link
  • Parent component route padding bit
<!-- cover vm The area controlled by the instance -->
<div id="app">
    <!-- 2. Add routing link -->
    <router-link to="/user">User</router-link>
    <router-link to="/register">Register</router-link>
    <!-- 3. Add route padding bit -->
    <!-- Route placeholder -->
    <router-view></router-view>
</div>

3.3 child routing template

  • Child routing link
  • Child route fill bit
 const Register = {
     template: `
         <div>
             <h1>Register assembly</h1>
             <hr/>
             <!-- Sub route link -->
             <router-link to="/register/tab1">tab1</router-link>
             <router-link to="/register/tab2">tab2</router-link>
             <!-- Placeholder for sub route -->
             <router-view />
         </div>
     `
 }

4. Nested routing configuration

  • The parent route configures the child route through the children attribute
// 5. Configure routing rules and create routing instances
// Create routing instance object
const router = new VueRouter({
    // routes is an array of routing rules
    routes: [
        // Each routing rule is a configuration object, which contains at least two attributes: path and component:
        // path indicates the hash address matched by the current routing rule
        // Component indicates the component to be displayed corresponding to the current routing rule
        // Where, path represents the original address to be redirected, and redirect represents the new address to be redirected
        { path: '/', redirect: '/user' },
        { path: '/user', component: User },
        {
            path: '/register',
            component: Register,
            children: [
                { path: '/register/tab1', component: Tab1 },
                { path: '/register/tab2', component: Tab2 }
            ]
        }
    ]
});

The complete code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- 1. Import related library files -->
    <!-- Import vue File, global window Object mount Vue Constructor -->
    <script src="./lib/vue_2.5.22.js"></script>
    <!-- Import vue File, global window Object mount Vue Constructor -->
    <script src="./lib/vue-router_3.0.2.js"></script>
</head>

<body>
    <!-- cover vm The area controlled by the instance -->
    <div id="app">
        <!-- 2. Add routing link -->
        <router-link to="/user">User</router-link>
        <router-link to="/register">Register</router-link>

        <!-- 3. Add route padding bit -->
        <!-- Route placeholder -->
        <router-view></router-view>
    </div>

    <script>
        // 4. Define routing components
        const User = {
            template: '<h1>User assembly</h1>'
        }

        const Register = {
            template: `
                <div>
                    <h1>Register assembly</h1>
                    <hr/>
                    <!-- Sub route link -->
                    <router-link to="/register/tab1">tab1</router-link>
                    <router-link to="/register/tab2">tab2</router-link>
                    <!-- Placeholder for sub route -->
                    <router-view />
                </div>
            `
        }

        const Tab1 = {
            template: '<h3>tab1 Subcomponents</h3>'
        }

        const Tab2 = {
            template: '<h3>tab2 Subcomponents</h3>'
        }

        // 5. Configure routing rules and create routing instances
        // Create routing instance object
        const router = new VueRouter({
            // routes is an array of routing rules
            routes: [
                // Each routing rule is a configuration object, which contains at least two attributes: path and component:
                // path indicates the hash address matched by the current routing rule
                // Component indicates the component to be displayed corresponding to the current routing rule
                // Where, path represents the original address to be redirected, and redirect represents the new address to be redirected
                { path: '/', redirect: '/user' },
                { path: '/user', component: User },
                {
                    path: '/register',
                    component: Register,
                    children: [
                        { path: '/register/tab1', component: Tab1 },
                        { path: '/register/tab2', component: Tab2 }
                    ]
                }
            ]
        });

        // 6. Mount the route to the Vue root instance
        const vm = new Vue({
            // Specifies the area to control
            el: '#app',
            data: {},
            // Mount routing instance object
            // router: router
            router
        });
    </script>
</body>

</html>

4. Vue router dynamic route matching

4.1 basic usage of dynamic matching routing

Application scenario: route matching through the mode of dynamic routing parameters

var router = new VueRouter({
	routes: [
		// Dynamic path parameters start with a colon
		{ path: '/user/:id', component: User }
	]
});
const User = {
	// Get routing parameters through $route.params in the routing component
	template: '<div>User {{ $route.params.id }}</div>'
}

4.2 routing component transfer parameters

$route is highly coupled with the corresponding route and is not flexible enough, so props can be used to decouple components and routes.

4.2.1 the value of props is Boolean

const router = new VueRouter({
	routes: [
		// If props is set to true, route.params will be set as the component property
		{ path: '/user/:id', component: User, props: true }
	]
});

const User = {
	props: ['id'], // Receive routing parameters using props
	template: '<div>user ID: {{ id }}</div>' // Use routing parameters
}

4.2.2 props value is object type

const router = new VueRouter({
	routes: [
		// If props is an object, it is set as is as a component property
		{ 
			path: '/user/:id', 
			component: User, 
			props: { uname: 'Li Si', age: 12 }
		}
	]
});

const User = {
	props: ['uname', 'age'],
	template: '<div>User information:{{ uname + '---' + age}}</div>'
}

In this case, the id value cannot be obtained through the following method.

4.2.3 the value of props is a function type

const router = new VueRouter({
	routes: [
		// If props is a function, this function receives the route object as its own formal parameter
		{ 
			path: '/user/:id',
			component: User,
			props: route => ({ uname: 'Zhang San', age: 20, id: route.params.id })
		}
	]
});

const User = {
	props: ['uname', 'age', 'id'],
	template: '<div>User information:{{ uname + '---' + age + '---' + id}}</div>'
}

5. Vue router named route

Configuration rules for named routes:

In order to more conveniently represent the route, you can give an alias to the routing rule, that is, "named route".

const router = new VueRouter({
	routes: [
		{
			path: '/user/:id',
			name: 'user',
			component: User
		}
	]
});
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
router.push({ name: 'user', params: { id: 123 }})

6. Vue router programmed navigation

6.1 two ways of page navigation

  • Declarative navigation: the way to navigate by clicking a link is called declarative navigation
    For example, < a > < / a > links in ordinary web pages or < router link > < / router link > in vue
  • Programmed navigation: the way to realize navigation by calling the API in the form of JavaScript is called programmed navigation.
    For example: location.href in a normal web page

6.2 basic usage of programmed navigation

Common programmatic navigation API s are as follows:

  • this.$router.push('hash address')
  • this.$router.go(n)
const User = {
	template: '<div><button @click="goRegister">Jump to the registration page</button></div>',
	methods: {
		goRegister: function(){
			// Control route jump by programming
			this.$router.push('/register');
		}
	}
}

6.3 programmed navigation parameter rules

Parameter rules of router.push() method

// String (path name)
router.push('/home')
// object
router.push({ path: '/home' })
// Named route (pass parameters)
router.push({ name: '/user', params: { userId: 123 }})
// With query parameters, it becomes / register?uname=lisi
router.push({ path: '/register', query: { uname: 'lisi' }})

Tags: Vue.js

Posted on Mon, 27 Sep 2021 05:33:48 -0400 by aahh