Vue Router – the use of routing, two switching methods, two parameter passing methods, and nesting methods

Table of Contents

1. Vue Router

1.1. Download

1.2. Basic use

a) Introduce vue-router.js (note: it must be introduced after Vue.js).

b) Create routing rules

c) Register into the Vue instance

d) Display routing components

1.3. Two ways to switch routes

1.3.1. Switching by label

1.3.2. Switch in js mode

1.3.3. There is a problem in switching the same route multiple times in VueRouter.

a) Solution 1: Manually judge before switching routes each time

1.4. Two parameter transmission methods

1.4.1. Passing parameters through querystring

1.4.2. Passing parameters through restful

1.5. Use of nested routing


1. Vue Router

1.1, download

Through Vue Router, existing Vue development can be made more flexible, allowing multiple different components to be displayed on one page.

The download address is as follows:

https://unpkg.com/vue-router/dist/vue-router.js

1.2, Basic use

a) Introduce vue-router.js (Note: To be introduced after Vue.js).

 <script src="../js/vue.js"></script>
    <!-- router must be introduced after vue.js -->
    <script src="../js/vue-router.js"></script>

b) Create routing rules

 //1. Create routing object
        const router = new VueRouter({
            //Configure routing rules:
            //path: represents the routing path ('#/' the route to be added after this hash route)
            //component: represents the component corresponding to the routing path
            //redirect: represents route redirection
            //path: "*" means matching all routes
            routes: [
                // { path: '/', component: login }, //Configure the default route (the login function is available as soon as the page is opened), but! The specification does not recommend that one component correspond to multiple routes
                { path: '/', redirect: '/login' }, //So you can redirect through redirect
                { path: '/login', component: login },
                { path: '/reg', component: register },
                { path: '*', component: notFound } //In the old version, this rule must be placed on the last line, but subsequent official optimization has been done, and it can be placed anywhere, but it is recommended to place it at the end.
            ]
        });

In actual projects, it is best to write an arrow function after the component, which can improve efficiency (lazy mode, loading only when used).

The best way to write it is as follows:

 //1. Create routing object
        const router = new VueRouter({
            //Configure routing rules:
            //path: represents the routing path ('#/' the route to be added after this hash route)
            //component: represents the component corresponding to the routing path
            //redirect: represents route redirection
            //path: "*" means matching all routes
            routes: [
                { path: '/', redirect: '/login' },
                { path: '/login', component: () => import('../views/Login') }, //Login here is the prefix of Login.vue
                { path: '/reg', component: () => import('../views/Reg') },
                { path: '*', component: () => import('../views/404') }
            ]
        });

The components defined here are as follows:

 const login = {
            template: `<div><h2>Login function</h2></div>`,
        }

        const register = {
            template: `<div><h2>Registration function</h2></div>`,
        }

        const notFound = {
            template: `<div><h2>404 not found The page has flown to outer space~</h2></div>`,
        }

c) Register in the Vue instance

 const app = new Vue({
            el: "#app",
            data: {
                msg: "Vue routing chapter"
            },
            router //2. Register route
        });

d) Display routing components

The router-view tag is used to render components

 <div id="app">

        <!-- 3. Display routing components -->
        <router-view></router-view>

    </div>

1.3. Two ways to switch routes

1.3.1, switch by label

 <!-- 1. Link -->
        <a href="#/login">Login</a>
        <a href="#/reg">Login</a>
        
        <!-- 2. The label must have the to attribute, to="routing path" -->
        <router-link to="/login">Login</router-link>
        <router-link to="/reg">Register</router-link>
        
        <!-- 3. Label -->
        <router-link :to="{path: '/login'}">Login</router-link>
        <router-link :to="{path: '/reg'}">Register</router-link>
        
        <!-- 4. Label switches routes according to the name attribute of the routing object -->
        <!-- Recommendation: The route may change at any time, but the naming will not, so it can play a role in decoupling -->
        <router-link :to="{name: 'Login'}">Login</router-link>
        <router-link :to="{name: 'Register'}">Register</router-link>

Following are the routing rules and components

 const login = {
            template: `<div><h1>Login function</h1></div>`
        }

        const register = {
            template: `<div><h1>Registration function</h1></div>`
        }

        //Create routing object
        const router = new VueRouter({
            routes: [
                //name represents the unique identity of this routing object
                { path: '/login', component: login, name: "Login" },
                { path: '/reg', component: register, name: "Register" },
            ]
        });

1.3.2, switch by js method

a) For example, trigger routing switching through a click event

 <button @click="loginSuccess()">One-click registration successful</button>
        <!-- Display component -->
        <router-view></router-view>

b) Register components and create routing rules

 const login = {
            template: `<div><h1>Login</h1></div>`
        }
        const reg = {
            template: `<div><h1>Registration</h1></div>`
        }
        const router = new VueRouter({
            routes: [
                { path: "/", redirect: "/reg" },
                { path: "/login", component: login, name: "Login" },
                { path: "/reg", component: reg, name: "Reg" },
            ]
        });

c) js switch route

 const app = new Vue({
            el: "#app",
            data: {
                msg: "js switch route"
            },
            methods: {
                loginSuccess() {
                    // this.$router.push("/login");//Not recommended
                    // this.$router.push({ path: '/login' });//Not recommended
                    this.$router.push({ name: "Login" });//It is recommended to use name switching
                }
            },
            router
        });

1.3.3. There is a problem when switching the same route multiple times in VueRouter

An error occurs when switching the same route multiple times in VueRouter, as follows:

There are two solutions, as follows:

First we need to know:

  • this.$route represents the current routing object route.
  • this.$router represents the routing manager object VueRouter.
a) Solution 1: Manually determine before each route switch
 const app = new Vue({
            el: "#app",
            data: {
                msg: "js switch route"
            },
            methods: {
                loginSuccess() {
                    //Solution to error when switching the same route multiple times in VueRouter:
                    //1. Make a manual judgment before each switch (not recommended, too troublesome)
                     if (this.$route.name != "Login") {
                         this.$router.push({ name: "Login" });
                     }

                }
            },
            router
        });

b) Solution 2: Official configuration

After creating the routing rule object, add the following configuration

 //2. Official configuration: Solve the problem of multiple switching errors for the same route in VueRouter
        const original = VueRouter.prototype.push;
        VueRouter.prototype.push = function push(location) {
            return original.call(this, location).catch(err => err)
        };

After that, you can directly write the method to switch routes.

 loginSuccess() {
                    this.$router.push({ name: "Login" });
                }

1.4, two parameter transmission methods

1.4.1, passing parameters through querystring

For example /login?name=cyk & amp;password=1111

a) The following four routing parameter transmission methods (the last one is recommended)

 <!-- query -->
        <a href="#/login?name=cyk & amp;password=123">Login</a>
        <router-link to="/login?name=cyk & amp;password=123">Login</router-link>
        <router-link :to="{path: '/login', query:{name:'cyk', password:1111}}">Login</router-link>
        <router-link :to="{name: 'Login', query:{name:'cyk',password:1111}}">Login</router-link>

b) Get parameters in the component as follows:

 const login = {
            template: `<div><h1>Login function</h1></div>`,
            created() { //Life cycle: Component internal events and life cycle function registration have been executed, and its own data, methods, computed attributes have been injected and verified
                //Get parameters through querystring
                console.log(this.$route); //Get the current routing object
                console.log(this.$route.query.name);
                console.log(this.$route.query.password);
            }
        }

c) The routing objects are as follows:

 //Create routing object
        const router = new VueRouter({
            routes: [
                //querystring passing parameters
                { path: '/login', component: login, name: "Login" }
            ]
        });

1.4.2, passing parameters through restful

For example /login/cyk/1111

a) The following three methods of passing parameters (the last one is recommended)

 <!-- restful -->
        <a href="#/register/6/lyj">Register</a>
        <router-link :to="{path: '/register/11/lyj'}">Register</router-link>
        <router-link :to="{name: 'Register', params:{id:11, name:'lyj'}}">Register</router-link>

b) Get parameters in the component as follows:

 const register = {
            template: `<div><h1>Registration function</h1></div>`,
            created() {
                //Get parameters through restful
                console.log(this.$route); //Get the current routing object
                console.log(this.$route.params.id);
                console.log(this.$route.params.name);
            }
        }

c) The routing objects are as follows:

 //Create routing object
        const router = new VueRouter({
            routes: [
                //querystring passing parameters
                { path: '/login', component: login, name: "Login" },
                //restful passing parameters
                { path: '/register/:id/:name', component: register, name: "Register" },
            ]
        });

1.5. Use of nested routing

When creating VueRouter, path also has a children parameter, which is used to define nested sub-component routes.

For example requirements:

1. Now there is a user list

2. When clicking “Add User Information”, the following dialog box is displayed

3. After clicking submit, return to user list routing

The implementation is as follows:

a) Define the component as follows

 <template id="users">
        <div>
            <h3>User list</h3>
            <router-link :to="{name:'adduser'}">Add user information</router-link>
            <table border="1">
                <tr>
                    <td>id</td>
                    <td>name</td>
                </tr>
                <tr>
                    <td>{<!-- -->{ users.id }}</td>
                    <td>{<!-- -->{ users.name }}</td>
                </tr>
            </table>
            <!-- Display nested subcomponents -->
            <router-view></router-view>
        </div>
    </template>

    <template id="add-user">
        <div>
            <div>
                <span>id: </span>
                <input type="text">
            </div>
            <div>
                <span>name: </span>
                <input type="text">
            </div>
            <button @click="submit()">Submit</button>
        </div>
    </template>

    <script>

        //user list
        const users = {
            template: '#users',
            data() {
                return {
                    users: [] //This cannot be written to death, you need to request the backend to get the parameters
                }
            },
            created() {
                //After the component is built, request the backend to get all the data of users and overwrite the empty array.
                this.users = { id: 1, name: 'cyk' }
            }
        }

        //Add user
        const adduser = {
            template: '#add-user',
            methods: {
                submit() {
                    //Send request to backend
                    //Switch routing after submission is completed
                    this.$router.push({ name: 'users' });
                }
            }
        }
    </script>

b) Create routing object

 //Create routing object
        const router = new VueRouter({
            routes: [
                {
                    path: '/users', component: users, name: 'users',
                    children: [ //Nested child component routing
                        //Note: In nested routing, sub-routes cannot start with /
                        { path: 'adduser', name: 'adduser', component: adduser } //This can be accessed through /users/useradd
                    ]
                },
            ]
        });

c) Register into the Vue instance

 const app = new Vue({
            el: "#app",
            component: {
                users,
                adduser
            },
            router
        });