The routing Router in Vue is from 0 ~ 0.5 basic knowledge to use (the basic use that the back-end personnel need to master)

📑 Content of this article: from 0 ~ 0.5 basic knowledge to use of routing Router in Vue (basic use that back-end personnel need to master)

📘 Article column: Front end knowledge (knowledge points to be mastered at the back end)

Front and rear end separation project (Vue + SpringBoot)

🎬 Last updated: January 29, 2022 Vue's life cycle entry to the grave is enough, which is suitable for the front-end knowledge of back-end personnel~

🙊 Personal profile: a Junior Program ape who is studying in a two-year college. In line with paying attention to foundation, clock in algorithm and sharing technology, as a blogger who summarizes personal experience, although he may be lazy sometimes, he will stick to it. If you like blog very much, it is suggested to look at the following line ~ (crazy hint QwQ)

🌇 give the thumbs-up 👍 Collection ⭐ Leaving a message. 📝 One key three connection care program ape, start with you and me

📑 Routing Router in Vue

🚀1,Vue Router

🎁 1. Introduction

Explanation of ecosystem on official website

Official learning documents: Vue Router (vuejs.org)

Vue Router can make the existing Vue development more flexible. It can load different components at different locations in the page according to the front-end request URL.

🎁 2. Installation and use

Download Vue router JS / NPM for installation

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

Right click Save as to save Vue router js

<script src="/js/vue.js"></script>
<script src="/js/vue-router.js"></script>

NPM installation

npm install vue-router

Get started quickly

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>01.Vue Router Basic use of.html</title>
</head>
<body>
    <div id="app">
        <!--Location of the render routing component-->
        <router-view></router-view>
    </div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script src="js/axios.min.js"></script>
<script>
    const login = {
        template: `<div><h3>Login Vue Router ~</h3></div>`
    }

    const register = {
        template: `<div><h3>Register Vue Router ~</h3></div>`
    }

    const router = new VueRouter({
        routes:[//Used to configure routing rules
            {path:'/login',component:login},
            {path: '/register',component: register}
        ]
    })

    const instance = new Vue({
        el: '#app',
        data:{},
        methods:{},
        computed:{},
        router//Register routing
    })
</script>

When debug ging through the browser, we can see the format with # / at the end of the page, which is usually called hash routing~

The usual steps are divided into four steps:

  • Step 1: create a template component, that is, define the template component object
const login = {
        template: `<div><h3>Login Vue Router ~</h3></div>`
    }
  • Step 2: add the template component object we created to the Vue route mapper. What must be written is the path address and the corresponding rendering component.
const router = new VueRouter({
        routes:[//Used to configure routing rules
            {path:'/login',component:login},
            {path: '/register',component: register}
        ]
    })
  • Step 3: register our route to the Vue instance

Note that the syntax abbreviation of ES6 is used here

const instance = new Vue({
        el: '#app',
        data:{},
        methods:{},
        computed:{},
        router//Register routing
    })
  • Step 4: the rendering location of the route needs to be marked in the page for rendering.
<router-view></router-view>

🎁 3. Basic syntax of Vue Router

const router = new VueRouter({
    routes:[
        {path: '/',component:login},
        {path:'/login',component:login},
        {path: '*',component:errorpage},
    ]
})

Path: represents the routing path.

Component: represents the component of route mapping.

redirect: represents the redirection of the route.

path: wildcard represents any route*

🎁 4. Path switching routing in Vue Router

<router-link to="/login">Sign in</router-link>
<router-link to="/register">register</router-link>
<router-view></router-view>

The corresponding switching of routing mapping is realized through labels

The underlying implementation principle is realized through the < a > tag

<a href='#/login'></a>

The above href route switching is based on the Hassy route, and # represents the route location from the current route to / login

So the methods used are consistent.

The object in Vue needs to be matched with the instance in Vue, and the object in Vue needs to be mapped correctly.

<router-link :to="{path:'/login'}">Sign in</router-link>
<router-link :to="{path:'/register'}">register</router-link>
<router-view></router-view>

Complete as above.

🎁 5. Name switch route in Vue Router

Switch routes by name: switch routes according to the names of routing objects, and display different components.

  • Step 1: add the name attribute to the component mapping in the corresponding router.
 const router = new VueRouter({
   routes:[//Used to configure routing rules
      {path:'/login',component:login,name:'Login'},
      {path: '/register',component: register,name:'Register'}
   ]
})
  • Step 2: bind the name attribute of the corresponding component in the corresponding to switch routes by name.
<router-link :to="{name:'Login'}">Sign in</router-link>
<router-link :to="{name:'Register'}">register</router-link>
<router-view></router-view>

⭐ 6. The routing in Vue Router is switched in JS ⭐

Take a small example 🌰:

When our user clicks the login button, the event triggered by the button will go to the server to request, get the data, complete the successful login operation, and switch the route to jump to the page after the response comes back.

When we add VueRouter to our Vue instance, two new properties will be displayed in the instance:

this.$router object current routing object:

{path:'/login',component:login,name:'Login'}

this.$router vueRouter represents the routing manager object:

methods:{
    login(){
        console.log(this);
        //this.$router.push('/login');
        //this.$router.push({path:'/login'});
        this.$router.push({name:'Login'});
    },
    register(){
       console.log(this);
       this.$router.push({name:'Register'});
    }
}

When we click the same route switch many times, the browser will report an error!!!

Official solutions:

1. It is implemented by suppressing route warning to prevent error reporting

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location){
    return originalPush.call(this,location).catch(function (err) {
        err;
    })
}

⭐ 7. Vue Router data parameter transfer ⭐

There are two ways to transfer parameters in the address bar:

  • queryString ?
<router-link :to="{path:'login?username=alascanfu&password=123456'}">Sign in</router-link>
<router-link :to="{name:'Login',query:{username:'alascanfu',password:'123456'}">register</router-link>

You can use this$ route. query. Key to get the parameter value of the specified key.

  • restful path pass parameters
<router-link :to="{path:'register/201901094106'}">Sign in</router-link>
<router-link :to="{name:'Register',params:{id:201901094106}}">register</router-link>

You can use this$ route. params. key

const router = new VueRouter({
        routes:[//Used to configure routing rules
            {path:'/login/:username/:password',component:login,name:'Login'},
            {path: '/register/:id',component: register,name:'Register'}
        ]
    })

⭐ 8. Vue Router nested routing ⭐

Where does nested routing come from? Why are there nested routes?

We can't show only one component on a view page! More often than not, we expect to display external border components, and change the displayed content components + external border components according to internal requirements.

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+

Code demonstration

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03.Vue Router Use of nested routing official website</title>
</head>
<body>
<div id="app">
    <router-view></router-view>
</div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script src="js/axios.min.js"></script>
<script>
    const User = {
        template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
    }
    const UserProfile = {
        template: `
    <div class="user">
      <h3>UserProfile {{ $route.params.id }}</h3>
    </div>
  `
    }

    const UserPosts = {
        template: `
    <div class="user">
      <h3>UserPosts {{ $route.params.id }}</h3>
    </div>
  `
    }

    const router = new VueRouter({
        routes: [
            {
                path: '/user/:id',
                component: User,
                children: [
                    {
                        // When / user/:id/profile matches successfully,
                        // The UserProfile will be rendered in the User's < router View >
                        path: 'profile',
                        component: UserProfile
                    },
                    {
                        // When / user/:id/posts match successfully
                        // UserPosts will be rendered in User's < router View >
                        path: 'posts',
                        component: UserPosts
                    }
                ]
            }
        ]
    })

    new Vue({
        el: '#app',
        router
    })
</script>

Note: the nested path does not need to be written with /, which mainly depends on the child [] attribute in the routing object. Note that the nested path starting with / will be regarded as the root path. This allows you to make full use of nested components without setting nested paths.

🙊 2. Summary

This time, Xiaofu once again sorted out the notes of the second brush Vue Router, combined with the official documents, and went through the basic use that the back-end personnel need to master. To deepen the use, we can quickly build the website in combination with some frameworks. In this aspect, we need to practice more in order to understand and be familiar with the use of Vue Router.

Keywords: Javascript Front-end Vue.js Back-end

Added by andylyon87 on Wed, 02 Feb 2022 20:00:19 +0200