This is my first day of the August Challenge

1. Quick concept:

1. Back-end routing:

1. Different contents are returned according to different URL requests, which is essentially the mapping between the URL request address and server resources.

2. However, there are performance issues with back-end rendering.

2. Front-end routing:

3. Hence the advent of Ajax pre-coding rendering, which improves performance but does not support browser forward and backward operations.

4. At this time, SPA (Single Page Application) appeared, the whole website has only one Page, the content changes through Ajax local update implementation, while supporting the browser address bar forward and backward operation.

5. One of the implementation principles of SPA is the HASH based on THE URL (The change of the hash will cause the change of the browser’s access history, but the change of the hash will not trigger new URL requests). In the process of realizing SPA, the most core technology is the front-end routing.

6. The front-end route displays different page contents based on different user events. The essence is the correspondence between user events and event handlers.

3. The Vue Router:

This is the official use document link.

The Vue Router is the official route manager of vue. js. Its deep integration with the vue.js core makes it very convenient for SPA application development.

Its functions are as follows:

1. Support HTML5 historical mode or hash mode. 2. Support embedded routine. 3. Route parameters are supported. 4. Support programmatic routing. 5. Named routes are supported.

Ii. Basic use:

Premise:

The following is a single HTML page that demonstrates the basic steps of using the Vue Router. The same principle applies to the Vue project. Current single page basic code:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    <script>
        const app = new Vue({
            el:"#app".data: {}})</script>
</body>
</html>
Copy the code

You can see nothing:

Here are the steps to start using:

1. Introduce relevant files:

The single page must first import the vue file and the vue-router file so that we can use routing.

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
Copy the code

2. Add a route link:

The following is a vUE tag that will be rendered as a tag by default. There is a to attribute, which is rendered as an href attribute, and the default value is rendered as a hash address beginning with #. In short, when the user clicks on different content, and this TAB is the user to click on, the equivalent of a TAB.

<router-link to="/..." >.</router-link>
Copy the code

Add a link to page1 and page2 to our single page:

<div id="app">
       <router-link to="/page1">Page1</router-link>
       <router-link to="/page2">Page2</router-link>
    </div>
Copy the code

3. Add a route configuration bit:

The tag below is called the route padding bit, which means that future components matched by our routing rules will be rendered to the router-View location. In simple terms, when a user clicks on a routing link, it will redirect to the content. We know that not the entire page will redirect, but the relevant part of the page will change. This part is the area where the router-view is displayed.

<router-view></router-view>
Copy the code

Add to our page:

 <div id="app">
        <router-link to="/page1">Page1</router-link>
       <router-link to="/page2">Page2</router-link>
       <router-view></router-view>
    </div>
Copy the code

4. Define routing components:

Since you want to display different content, you must use one component to save one content. Let’s define page1 and Page2 for a single page.

 <script>
        const Page1 = {
            template: '

I'm Aurora Borealis Night 1

'
} const Page2 = { template: '

I'm Aurora Borealis Night # 2

'
} const app = new Vue({ el:"#app".data: {}})
</script> Copy the code

5. Configure a routing rule well to create a routing instance:

Routes is an array of routing rules. Each routing rule is a configuration object that contains at least two attributes: PATH, the hash address that the current routing rule matches, and Component, the component that the current routing rule matches. In simple terms, you click on the link corresponding to the address of the corresponding component of the content. Make sure the path is the same as the address in the router-link TAB.

const router = new VueRouter({
            routes: [{path:'/page1'.component:Page1 },
                {path:'/page2'.component:Page2 }
            ]
        })
Copy the code

6. Mount the route to the Vue root instance:

In order for the routing rule to take effect, the routing object must be mounted to the VUE instance object.

 const app = new Vue({
            el:"#app".data: {},
            router
        })
Copy the code

7. Effects and single page code:

Above we complete the work ~

The full code above:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <! -- import vue file -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
       <router-link to="/page1">Page1</router-link>
       <router-link to="/page2">Page2</router-link>
       <router-view></router-view>
    </div>
    <script>
        const Page1 = {
            template: '

I'm Aurora Borealis Night 1

'
} const Page2 = { template: '

I'm Aurora Borealis Night # 2

'
} const router = new VueRouter({ routes: [{path:'/page1'.component:Page1 }, {path:'/page2'.component:Page2 } ] }) const app = new Vue({ el:"#app".data: {}, router })
</script> </body> </html> Copy the code

Route redirection:

Route redirection means that when A user accesses address A, the user is forced to jump to address B to display A specific component page. Using the Redirect attribute of the routing rule, you can specify a new routing address to easily set the redirection of the route.

{path:'/.. '.redirect: '/... '}
Copy the code

Path indicates the original redirection address, and redirect indicates the new address.

For example, in the second point case, the page you just opened is like this, in the root directory, but we want to show page1 as soon as we enter, so we redirect to the root directory.

Modify the routing rules as follows:

 const router = new VueRouter({
            routes: [{path:'/page1'.component:Page1 },
                {path:'/page2'.component:Page2 },
                {path:'/'.redirect:'/page1'}]})Copy the code

I’m going to default to Page1 if I don’t click:

Iv. Set routines by:

Functions are as follows:

  1. Click the parent route link to display the template content.
  2. The template content has child routing links.
  3. Click the child route link to display the child template content.

For example, we improve the case of the second biggest point. When clicking Page2 to display page2 content, there are two child routes in Page2, star and Moon. When clicking one of the links, the corresponding star or Moon content can be displayed.

1. First add two child route links to the Page2 component:

const Page2 = {
            template: '
      

I'm Aurora Borealis Night 2


star Moon
`
} Copy the code

At this point, the page also displays the child route link:

2. Add a route population bit to the two child route links:

  const Page2 = {
const Page2 = {
            template: '
      

I'm Aurora Borealis Night 2


star Moon
`
} Copy the code

3. Set the content of the two sub-components star and Moon:

       const Star = {
            template: ' 

} const Moon = { template:

} Copy the code

4. Configure routing rules.

In page2, in addition to the Path and Component attributes, add a children attribute. This attribute is represented by an array. The array stores the rules for its child routes, and the rules are the same, nesting dolls nesting dolls.

const router = new VueRouter({
            routes: [{path:'/page1'.component:Page1 },
                {
                    path:'/page2'.component:Page2, 
                    children: [{path: '/page2/star'.component:Star},
                        {path: '/page2/moon'.component:Moon}
                    ]
                }
            ]
        })
Copy the code

5. Effects and single page code:

Complete code:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <! -- import vue file -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
       <router-link to="/page1">Page1</router-link>
       <router-link to="/page2">Page2</router-link>
       <router-view></router-view>
    </div>
    <script>
        const Page1 = {
            template: '<h1>I'm Northern Lights night 1</h1>'
        }
        const Page2 = {
            template: `
                 <div>
                 <h1>This is Northern Lights Night number two</h1>
                 <hr/>
                 <router-link to="/page2/star">Star</router-link>
                 <router-link to="/page2/moon">Moon</router-link>
                 <hr/>
                 <router-view></router-view>
                 </div>`
        }
        const Star = {
            template: '<h2>I'm the star of northern Lights Night 2</h2>'
        }
        const Moon = {
            template: '<h2>I'm Moon on northern Lights Night 2</h2>'
        }
        const router = new VueRouter({
            routes: [
                {path:'/page1',component:Page1 },
                {
                    path:'/page2',
                    component:Page2, 
                    children: [
                        {path: '/page2/star',component:Star},
                        {path: '/page2/moon',component:Moon}
                    ]
                }
            ]
        })
        const app = new Vue({
            el:"#app",
            data: {},
            router
        })
    </script>
</body>
</html>
Copy the code

5. Dynamic route matching:

1. Basic usage of dynamic matching routes:

If one part of some routing rules is the same, and only the other part changes dynamically, then we can form these dynamically changing parts into routing parameters, and these parameters are called dynamic routing matching. In short, if you look at the following routing links, they all have /page/, but the latter is different:

   <router-link to="/page/1">Page1</router-link>
   <router-link to="/page/2">Page2</router-link>
   <router-link to="/page/3">Page3</router-link>
Copy the code

So how do you configure routing? Do this:

const router = new VueRouter({
            routes: [{path:'/page/1'.component:Page},
                {path:'/page/2'.component:Page},
                {path:'/page/3'.component:Page}
            ]
        })
Copy the code

In this case, it would be too troublesome to write many of them, so introduce parameters, in the dynamic change part of the parameter defined as parameter, there is a colon in front of the parameter, the above can be abbreviated as follows, dynamic part of the parameter: id.

const router = new VueRouter({
            routes: [{path:'/page/:id'.component:Page },
            ]
        })
Copy the code

The parameters of the current route can be obtained from the component using the following syntax:

$router-params. parameter nameCopy the code

Ok, modify the case of the second largest point again to complete dynamic route matching:

1. Define routing links:

<div id="app">
   <router-link to="/page/1">Page1</router-link>
   <router-link to="/page/2">Page2</router-link>
   <router-link to="/page/3">Page3</router-link>
   <router-view></router-view>
   </div>
Copy the code

2. Dynamic route configuration, parameter ID:

const router = new VueRouter({
    routes: [{path:'/page/:id'.component:Page1 },
    ]
})
Copy the code

3. Set component content and display the parameters of the current route:

const Page1 = {
    template: {{$route.params.id}}'
}
Copy the code

See the effect:

2. Routing component parameters:

$route: functions: functions: functions: functions: functions: functions: functions: functions In short, there seems to be nothing to say, just look at the following example to understand.

2.1 When props is of the Boolean type:

        const router = new VueRouter({
            routes: [
 // Set props. If props is true, router.params will be set as a component property
                {path:'/page/:id'.component:Page1,props: true]})},const Page1 = {
// At this point, we'll use props to receive the parameter ID and use it
                    props: ['id'].template: '

I'm Aurora Borealis Night # 1, current ID: {{id}}

'
} Copy the code

To achieve the same effect, but with more flexibility, remember to configure routing rules the other way around, defining components first, just for the sake of intuition:

2.2 When props is an object type:

            const Page1 = {
        // At this point, we'll use props to receive the parameter object and display it
                props: ['name'.'age'].template: ` < h1 > I am the night of the aurora borealis 1, the current id is: {{id}} < hr / > name is: {{name}}, age is: {{age}} < / h1 > `
                }
             const router = new VueRouter({
                routes: [
            // props is a parameter object that will be set as the component property,
            // All custom parameters can be passed, but id cannot be passed
                    {path:'/page/:id'.component:Page1 , props: {name:'auroras'.age: 18}}}])Copy the code

Effects, props, props

2.3 When the function type is props:

This one can get everything.

    const Page1 = {
// At this point, we'll use props to receive the parameters
        props: ['name'.'age'.'id'].template: ` < h1 > I am the night of the aurora borealis 1, the current id is: {{id}} < hr / > name is: {{name}}, age is: {{age}} < / h1 > `
        }
     const router = new VueRouter({
        routes: [
    // props. This object takes the router object as its parameter.
    // Customizable parameters and ids can be passed
            {path:'/page/:id'.component:Page1 , 
            props: router= > ({id: router.params.id,name:'auroras'.age: 18}})})Copy the code

Effect:

Current complete code:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <! -- import vue file -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <router-link to="/page/1">Page1</router-link>
        <router-link to="/page/2">Page2</router-link>
        <router-link to="/page/3">Page3</router-link>
        <router-view></router-view>
        </div>   
         <script>
            const Page1 = {
        // At this point, we can use props to receive the parameter object
                props: ['name'.'age'.'id'].template: ` < h1 > I am the night of the aurora borealis 1, the current id is: {{id}} < hr / > name is: {{name}}, age is: {{age}} < / h1 > `
                }
             const router = new VueRouter({
                routes: [
            // props. This object takes the router object as its parameter.
            // Customizable parameters and ids can be passed
                    {path:'/page/:id'.component:Page1 , 
                    props: router= > ({id: router.params.id,name:'auroras'.age: 18}})})const app = new Vue({
            el:"#app".data: {},
            router
        })
    </script>
</body>
</html>
Copy the code

Vi. Vue-router Named route:

To conveniently represent the route path, you can alias the routing rule named Route. Continue to improve the above example usage:

1. Add a name attribute to the routing rule. This attribute is the alias:

 const router = new VueRouter({
    routes: [{name: 'user'.path:'/page/:id'.component:Page1 , 
        props: router= > ({id: router.params.id,name:'auroras'.age: 18}})})Copy the code

2. Use:

     <div id="app">
    <router-link :to="{name:'user',params: {id: 1}}">Page1</router-link>
    <router-link to="/page/2">Page2</router-link>
    <router-link to="/page/3">Page3</router-link>
    <router-view></router-view>
    </div>   
Copy the code

Let’s improve the first routing link by adding a colon before the to, where the name indicates the routing rule to be matched, and the params indicates the parameter to be passed. See the same effect:

7. Programmatic navigation:

  1. Declarative navigation: First, declarative navigation is the way the user navigates by clicking on links, such as a TAB or a route link.
  2. Programmatic navigation: Programmatic navigation is a jump because I click on it, it’s not a link, but it calls an API in JavaScript that also implements a jump.
  3. Common programmatic navigation apis are as follows:
this.$router.push('Hash address to jump to')
this.$router.go(n)
Copy the code

Push directly put the hash address to jump, go method to achieve forward and back, n represents the array, if n is 1 means forward in history, -1 means back in history.

1. This. $router. Push (‘ ‘) :

Rewrite an example where there are three routing links, page1, Page2, and page3, and there is a button in Page3 that is clicked to display the contents of Page1. This button is not a link in declarative navigation, it’s just a button.

1. Define a common route link:

    <div id="app">
    <router-link :to="/page/1">Page1</router-link>
    <router-link to="/page/2">Page2</router-link>
    <router-link to="/page/3">Page3</router-link>
    <router-view></router-view>
    </div>   
Copy the code

2. Define the three component content, which put a button to page3 components, and bind the click event, in the event through the API to navigate to page1:

const Page1 = {
    template: '

I'm Aurora Borealis Night 1

'
} const Page2 = { template: '

I'm Northern Lights Night # 2

'
} const Page3 = { template:

< button@click ="goPage1"> return page1
'
.methods: { goPage1(){ this.$router.push('/page/1')}}}Copy the code

3. Routing rules:

const router = new VueRouter({
                routes: [{path:'/page/1'.component: Page1},
                    {path:'/page/2'.component: Page2},
                    {path:'/page/3'.component: Page3}
                ]
             })  
Copy the code

4. Watch the effect:

5. Complete code:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <! -- import vue file -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <router-link to="/page/1">Page1</router-link>
        <router-link to="/page/2">Page2</router-link>
        <router-link to="/page/3">Page3</router-link>
        <router-view></router-view>
    </div>   
         <script>
            const Page1 = {
                template: '

I'm Aurora Borealis Night 1

'
} const Page2 = { template: '

I'm Northern Lights Night # 2

'
} const Page3 = { template:

< button@click ="goPage1"> return page1
'
.methods: { goPage1(){ this.$router.push('/page/1')}}}const router = new VueRouter({ routes: [{path:'/page/1'.component: Page1}, {path:'/page/2'.component: Page2}, {path:'/page/3'.component: Page3} ] }) const app = new Vue({ el:"#app".data: {}, router })
</script> </body> </html> Copy the code

In addition to the href path, you can also perform the following operations:

// String (path name)
router.push('/page1')
Copy the code
// Object form
router.push({path: '/page1'})
Copy the code
// You can also pass the parameter named route
router.push({name: '/page1'.parmas: {id: 1}})
Copy the code
// With query parameter, change to /page1? p=id
// This is useful. For example, in some music pages, after clicking on a playlist, you need to navigate to another playlist detail interface. At this time, you need to bring an ID
router.push({parh: '/page1'.query: {p: 'id' }})
Copy the code

2. This. $router. Go (n) :

To improve on the first smaller case, when I jump from page3 to Page1, page1 has a return button again. If we set n to -1, he will fall back one place in the history, which is Page3. Modify the contents of page1 components:

  const Page1 = {
                template: ` < div > < h1 > I am the night of the aurora borealis 1 < / h1 > < button @ click = "goBack" > return < / button > < / div > `.methods: {
                    goBack(){
                        this.$router.go(-1)}}}Copy the code

Effect:

Viii. Conclusion:

When will the epidemic end? I want to travel.

See you next time