Introduction: Due to the lack of routing support in Vue at the time of development, the vue-Router plug-in was officially added. It is very important in the Vue ecosystem. In the actual development, as long as you write a page, you can operate vue-Router. To learn vue-router, you need to know what is the route here? The routing here is not a hardware router as we normally call it, the routing here is a SPA (single page application) path manager. More commonly, vue-Router is the link path management system of WebApp.

  • Some friends will have doubts, why can’t we write links with tags as before? Since we use Vue as a single-page application, which is equivalent to having only one main index.html page, the tags you write don’t work, you have to use vue-Router to manage them.

Vue – introduction to the router

Install the vue – the router

Vue-router is a plug-in package, so we still need NPM to install it.

NPM install vue-router –save-dev If you are slow to install, you can also use CNPM to install vue-router. If you have already installed vue-router using vue-CLI, you do not need to repeat the installation.

1Unscramble the router/index.js file

  • We used vue-CLI to produce our project structure, which you can find in the SRC /router/index.js file, which is the core routing file. Let’s take a look at it first.
import Vue from 'vue'   / / into the Vue
import Router from 'vue-router'  Vue / / in the router
import Hello from '@/components/Hello'  // Import the hello. vue component in the root directory

Vue.use(Router)  //Vue uses Router globally

export default new Router({
  routes: [              // Configure the route. This is an array
    {                    // Each link is an object
      path: '/'.// Link path
      name: 'Hello'.// Route name,
      component: Hello   // The corresponding component template}]})Copy the code

The only function configured in this routing file is to display the content code in Hello.vue when entering the project.

2Add a Hi route and page

Once we are familiar with the core routing file, we try to add a routing configuration. We want a new page to appear when we type http://localhost:8080/#/hi in the address bar.

Specific operation steps:

In the SRC/Components directory, create a new hi. vue file. To write the contents of the file, as we discussed earlier, the file should have three parts

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am Drgon brother'}}}</script>


<style scoped>

</style>
Copy the code

Import Hi from ‘@/components/Hi’ to router/index.js Add a new object to the Routes [] array in the router/index.js file.

{
path:'/hi'.name:'Hi'.component:Hi
}
Copy the code

Complete routing configuration file:

import Vue from 'vue'   / / into the Vue
import Router from 'vue-router'  Vue / / in the router
import Hello from '@/components/Hello'  // Import the hello. vue component in the root directory
import Hi from '@/components/Hi' 

Vue.use(Router)  //Vue uses Router globally

export default new Router({
  routes: [              // Configure the route. This is an array
    {                    // Each link is an object
      path: '/'.// Link path
      name: 'Hello'.// Route name,
      component: Hello   // The corresponding component template}, {path:'/hi'.name:'Hi'.component:Hi
    }
  ]
})
Copy the code

Router-link Creates the navigation


To: is our navigation path, which is specified in the router/index.js file. If you want to navigate to the default home page, just write to= “/”.

[Display field] : is the navigation name we want to display to the user, such as the home news page. Now that we know the basic syntax of router-link, we add the following code to the template in the SRC/app. vue file to implement navigation.

<p> navigation: <router-link to="/"> home page < / router - the link ><router-link to="/hi">Hi page</router-link>
</p>
Copy the code

Now we go to the page and we see that we have added navigation.

Vue-router Configures child routes

  • The case of child routing is generally used when a page has its base template, and then the pages below it all belong to that template, only partially changing the style. Following the example of the first lesson, create two new sub-pages under the Hi page, respectively “Hi page 1” and “Hi page 2”, to implement the sub-routing.

1. Modify the navigation code of app. vue

We need to transform the navigation code of app.vue first to realize the basic navigation function. We added two new navigation links using tabs.

App. Vue code

<p> navigation: <router-link to="/"> home page < / router - the link > |<router-link to="/hi">Hi page</router-link> |
      <router-link to="/hi/hi1">Page 1 - Hi</router-link> |
      <router-link to="/hi/hi2">Page 2 - Hi</router-link>
</p>
Copy the code

When we visit the home page again, the navigation bar has changed. There are two more self-navigation: Hi page 1 and Hi page 2

Rewrite the components/ hi. vue page

Make hi. vue a generic template and add tags to provide insert locations for child templates. “Hi page 1” and “Hi page 2” are both child pages of “Hi page”, sort of trying to inherit. We added tags to the “Hi page”.

Components/hi. vue is the code on line 5, leaving everything else unchanged

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>

    <router-view class="aaa"></router-view>
  </div>
</template>

<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am JSPang'}}}</script>
<style scoped>

</style>
Copy the code

Create two component templates hi1. vue and hi2. vue in the components directory

The new template is not much different from Hi.vue. Knowledge changes the value of message in data, meaning that the output is different. Hi1.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am Hi1! '}}}</script>
<style scoped>

</style>
Hi2.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am Hi2'}}}</script>
<style scoped>
</style>
Copy the code

We now have the navigation, the parent and child templates, and we just need to change our routing configuration file. The children field is added to the original route configuration.

children:[
        {path:'/'.component:xxx},
        {path:'xx'.component:xxx},
]
Copy the code

The children field is followed by an array, which is basically the same as the other configured routes. You need to configure path and Component. Take a look at the configuration of this subroute.

import Vue from 'vue'   
import Router from 'vue-router'  
import Hello from '@/components/Hello'  
import Hi from '@/components/Hi' 
import Hi1 from '@/components/Hi1' 
import Hi2 from '@/components/Hi2' 

Vue.use(Router) 

export default new Router({
  routes: [{path: '/'.name: 'Hello'.component: Hello   
    },{
      path:'/hi'.component:Hi,
      children:[
        {path:'/'.component:Hi},
        {path:'hi1'.component:Hi1},
        {path:'hi2'.component:Hi2},
      ]
    }
  ]
})
Copy the code

Note that before configuring the routing file, import Hi1 and Hi2.

How does vue-router pass parameters

Parameter passing is a fundamental business requirement in development. Passing parameters by URL address is a formality, so let’s look at what vue-Router provides for passing parameters. Let’s imagine a basic requirement that when we click on the navigation menu, the path of the current page is displayed on the jump page to tell the user where you want to see the page (similar to breadcrumb navigation).

Pass the parameter by name

In the last two videos, the name option was always there, but we didn’t talk about it. In this video, we’re going to talk about one function of name, passing parameters. And then we continue to write the program that we did last time.

Pass the value by name and display it in the template in two steps:

Configure the name attribute in the route file SRC /router/index.js.

routes: [
        {
          path: '/'.name: 'Hello'.component: Hello
        }
]
Copy the code

SRC/app.vue: $route.name: $route.

{{ $route.name}}

Pass the parameter through the to tag

In fact, most of our parameters are not passed by name. We use the to attribute in the tag to pass the parameter. What you need to notice is that there is a binding for the parameter to, which is written as :to. Let’s look at the basic syntax of this parameter passing method:

<router-link :to="{name:xxx,params:{key:value}}">valueString</router-link>

Here “to” is preceded by a colon, followed by a string of object situations.

Name: is the name value we start in the routing configuration file.

Params: That’s the argument we’re passing. It’s also an object situation. You can pass multiple values in an object. Now that we know the basic syntax, let’s change the

tag in SRC/app. vue. Let’s change the

tag in hi1.

<router-link :to="{name:'hi1',params:{username:'jspang'}}">

SRC /reouter/index.js name the route configured by hi1.

{path:'/hi1',name:'hi1',component:Hi1}

SRC /components/ hi1.vue $route.params.username

{{$route.params.username}}

Conclusion: Today we have learned two ways to pass parameters, the second method will be used. We also know the use of name through learning. One function is to transmit parameters, and the other function is to play the role of name in the transmission of parameters. The operation of passing parameters is a basic requirement in real development.

Section 4: Single page multiple Routing area operation

<router-view>

Tag, and add some CSS styles.



<router-view ></router-view>
 <router-view name="left" style="float:left; width:50%; background-color:#ccc; height:300px;"></router-view>
 <router-view name="right" style="float:right; width:50%; background-color:#c0c; height:300px;"></router-view>
Copy the code
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Hi1 from '@/components/Hi1'
import Hi2 from '@/components/Hi2'

Vue.use(Router)

export default new Router({
  routes: [{path: '/'.components: {
        default:Hello,
        left:Hi1,
        right:Hi2
      }
    },{
      path: '/Hi'.components: {
        default:Hello,
        left:Hi2,
        right:Hi1
      }
    }

  ]
})
Copy the code

In the above code we wrote two paths, one of which is the default ‘/’ and the other is’ /Hi ‘. In components under both paths, we define display content for all three areas. Once defined, we need to create hi1. vue and hi2. vue pages in the Component folder.

Hi1.vue

<template>
    <div>
        <h2>{{ msg }}</h2> 
    </div>
</template>

<script>
export default {
  name: 'hi1',
  data () {
    return {
      msg: 'I am Hi1 page.'}}}</script>
Hi2.vue

<template>
    <div>
        <h2>{{ msg }}</h2>
    </div>
</template>

<script>
export default {
  name: 'hi2',
  data () {
    return {
      msg: 'I am Hi2 page.'}}}</script>
Copy the code

Finally, we can configure our

in app.vue

<router-link to="/"> home page < / router - the link > |<router-link to="/hi">Hi page</router-link> |
Copy the code

Section 5: Vue-router passes parameters using urls

: Passes arguments as colons

We can bind parameters by passing them as: colons in the reasons configuration file. -. Set parameters with colons in the configuration file. We configure the route in/SRC /router/index.js.

{
    path:'/params/:newsId/:newsTitle'.component:Params
}
Copy the code

The parameters we need to pass are the newsId (newsId) and the newsTitle (newsTitle). So we specify these two values in the routing configuration file.

Create our params.vue component, or page, in the SRC/Components directory. We output the news ID and title of the NEWS delivered by the URL in the page.

<template>
    <div>
        <h2>{{ msg }}</h2>
        <p>{{$route.params.newsId}}</p>
        <p>{{$route.params.newstitle}}</p>
    </div>
</template>

<script>
export default {
  name: 'params',
  data () {
    return {
      msg: 'params page'}}}</script>
Copy the code

Add our tags to the app.vue file. At this point we can directly use the URL to pass the value. Params | we’ve implemented by value on the basis of the url, it is often used in the actual development, must fully understand. I hope you can practice both sides after watching the video or learning the article, and use them fully in the actual project.

The application of regular expression in URL transmission

In the example above, we passed the news number, now we need to upgrade, we want to pass the news ID only numeric form, in this case we need to pass a basic type judgment, VUE supports re.

To add a re, you need to add it in parentheses in the route configuration file (/ SRC /router/index.js).

Path :’/params/:newsId(\\d+)/:newsTitle’ adds the re, and we pass parameters other than numbers that the params.vue component cannot receive.

Vue-router redirection-redirect

Sometimes we want to jump to the same page, or open the same component, even though we have different paths. This is where the redirect parameter of the route is used.

Redirect Basic redirection

Simply change the component to redirect in the route configuration file (/ SRC /router/index.js). Let’s look at a simple configuration.

export default new Router({
  routes: [{path: '/'.component: Hello
    },{
      path:'/params/:newsId(\\d+)/:newsTitle'.component:Params
    },{
      path:'/goback'.redirect:'/'}]})Copy the code

Here we set up the goback route, but it does not configure any component. It redirects directly to the path: ‘/’. This is a simple redirect.

Pass parameters when redirecting

We’ve learned to pass parameters through urls, so what if we also need to pass parameters when we redirect? In fact, vue is already set up for us, we just need to copy the redirection path parameter in the parameter after ridirect. In case you’re confused, let’s look at this code:

{
  path:'/params/:newsId(\\d+)/:newsTitle'.component:Params
},{
  path:'/goParams/:newsId(\\d+)/:newsTitle'.redirect:'/params/:newsId(\\d+)/:newsTitle'
}
Copy the code

Now that we have a Params routing configuration, we are setting up a route redirection for goParams and passing the parameters. At this point our routing parameters can be passed to the params.vue component. The parameter receiving method is the same as the normal route receiving method.

Alias Indicates the use of an alias

/ SRC /router/index.js; / SRC /router/index.js; / SRC /router/index.js

{
    path: '/hi1'.component: Hi1,
    alias:'/jspang'
 }
Copy the code

2. Configure our to alias, can directly use the to attribute in the tag, redirection.

<router-link < to="/jspang">jspang</router-link>

Difference between Redirect and alias

Redirect: Take a close look at the URL. Redirect directly changes the URL’s value to the actual path. Alias: The URL path does not change. This is a friendlier situation, letting users know where they are going, but changing the content in the URL. Do not use aliases with path ‘/’. Aliases with the following code will not work.

{
      path: '/'.component: Hello,
      alias:'/home'
}
Copy the code

In a real project we ran into a pit like this and thought that there was something wrong with our code and spent two hours working on it. It turns out it’s not a code problem, but vUE doesn’t support it. We have made mistakes and stepped on the pit, I hope you will not step on it.

Transition animation of routes

In the development of a demand for high-end, atmospheric, grade. So it’s your responsibility as a big front-end to make your application cool to run. We can add some animation effects during page switching to improve the dynamic design of our program. In this lesson we will learn the transition animation of the route.

< the transition > tag

To make way for a transition animation, you need to add a
tag to the

tag. The tag also needs a name attribute.

<transition name="fade">
  <router-view ></router-view>
</transition>
Copy the code

We added a tag to the/SRC/app. vue file and called it fade.

CSS transition class name

During the transition, there will be four CSS class names related to the transition name attribute. For example, name= “fade”, there will be four CSS class names:

Fade – Enter: enters the beginning state of transition, which takes effect when an element is inserted, and is deleted immediately after only one frame is applied.

Fade -enter-active: Enters the end state of the transition. The element takes effect as soon as it is inserted and is removed after the transition process is completed

Fade -leave: the state at the beginning of the transition, triggered when the element is deleted and immediately deleted after only one frame is applied.

Fade -leave-active: The end state of the exit transition, which takes effect when the element is deleted and will be deleted after the exit transition is completed.

As you can see from the above four class names, the fade-enter-active and fade-leave-active are valid for the entire entry and exit process, so the TRANSITION property of the CSS is set under these two classes.

Let’s add four CSS styles to the app. vue page and use the TRANSITION property of CSS3 to control how the animation looks. The code is as follows:

.fade-enter {
  opacity:0;
}
.fade-leave{
  opacity:1;
}
.fade-enter-active{
  transition:opacity .5s;
}
.fade-leave-active{
  opacity:0;
  transition:opacity .5s;
}
Copy the code

The above code sets the animation transition to change transparency, but the default mode in-out mode is not what we want. Let’s look at the mode mode.

Transition mode:

In-out: The new element enters the transition first, and the current element transitions out after completion. Out-in: The current element transitions out first, and the new element transitions in after leaving. This lesson can only be a simple introduction to transition, teaching you the principle, if you want to make a practical and cool transition effect, you need to have strong animation ability, we will continue to learn animation knowledge next class.

Section 9: Mode Settings and 404 Page Handling We learned about mode Settings when we looked at transitions, but there is also a mode in the attributes of the route. In this lesson we will look at another mode and 404 page Settings.

Two values of mode

Histroy: When you use history mode, urls look like normal urls, such as http://jsapng.com/lms/!

Hash: The default ‘hash’ value, but hash looks like a nonsensical arrangement of characters, which is not pretty and doesn’t fit our general web browsing habits.

I will cover up the specific effect in the video. If you don’t understand, you can check it in the video.

404 page Settings

Users often make mistakes, and when they make mistakes, we want to give them a friendly reminder. For this reason, artists design a beautiful page, which is often referred to as a 404 page. Vue-router also provides this mechanism for us.

1. Set up our route configuration file (/ SRC /router/index.js) :

{path: “, Component :Error} path: “is the configuration when the page is not found. Component is a new error. vue file.

2. Create a 404 page:

Create a new error. vue file in the/SRC /components/ folder. Simply enter something about the error page.

<template>
    <div>
        <h2>{{ msg }}</h2>
    </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'Error:404'}}}</script>
Copy the code

3. We are writing a path with a label.

I’m blind to write | preview we now as a result, the already realize the effect of 404 pages.

We know that a component has many hook functions from entry to destruction, and hook functions are also set up in the route. The hook options for the route can be written in the route configuration file or in our component template. In this lesson, we will introduce the two types of hook functions.

Hook functions in the routing configuration file

We can write the hook function directly in the route configuration file (/ SRC /router/index.js). But we can only write one beforeEnter in the routing file when entering this routing configuration. Let’s take a look at some specific code:

{
      path:'/params/:newsId(\\d+)/:newsTitle'.component:Params,
      beforeEnter:(to,from,next) = >{
        console.log('I'm in the Params template');
        console.log(to);
        console.log(from);
        next();
},
Copy the code

We have configured the bdforeEnter hook function in the params route. The function uses the arrow function of ES6 and needs to pass three parameters. We also print the to and FROM functions in the arrow function. You can view object on the console.

Three parameters:

To: Indicates the information about the route to be jumped. The information is contained in the object.

From: Indicates the path information before the jump, also in the form of an object.

Next: Indicates the control parameter of the route. Common ones are next(True) and next(false).

A hook function written in a template

In the configuration file, there is only one hook -beforeEnter, there are two hook functions that can be used if we write them in the template:

BeforeRouteEnter: Hook function before route entry. BeforeRouteLeave: The hook function before the route leaves.

export default {
  name: 'params',
  data () {
    return {
      msg: 'params page'}},beforeRouteEnter:(to,from,next) = >{
    console.log("Ready to enter route template");
    next();
  },
  beforeRouteLeave: (to, from, next) = > {
    console.log("Prepare to leave route template");
    next();
  }
}
</script>
Copy the code

This is the route hook function we wrote in the params.vue template. It can monitor incoming and outgoing routes and easily read to and from values.

Programmatic navigation

This is the last section of this article. The navigation in the first 10 articles is completed in the form of

tag or direct operation of the address bar. What should we do if we need to jump to a page in the business logic code? This is what we mean by programmatic navigation, which, as the name implies, is navigation in business logic code.

this.
r o u t e r . g o ( 1 ) and t h i s . The router. The go (1) and this.
router.go(1)

These two programmatic navigations, which mean back and forward, function like the back and forward buttons on our browsers, which are often used in business logic. For example, if the conditions are not met, we need to back off.

Router.go (-1) represents a step back, we can make our navigation step back, and our address bar changes as well.

1. We’ll add a button to our app.vue file and bind it to a goback() method.

< button@click =”goback”> < button@click =”goback”> < button@click =”goback”> < button@click =”goback”>

<script>
export default {
  name: 'app'.methods: {goback(){
      this.$router.go(-1);
    }
  }
}
</script>
Copy the code

Open the browser for a preview, and our back button will now go back just like the previous page.

Router. Go (1): router. Go (1): router.

This $router. Push (‘/’) XXX

This programmatic navigation is used to jump, for example, when we judge that the user name and password is correct, we need to jump to the user center page or the home page, all use this programming method to operate routing.

We set up a button that takes us back to the front page.

1. Start by writing a button that binds the goHome() method to it.

2 in

export default {
  name: 'app'.methods: {goback(){
      this.$router.go(-1);
    },
    goHome(){
      this.$router.push('/'); }}}Copy the code

Personal notes

Slot: named slot, anonymous slot, scoped slot (slots can use dynamic data, slots can use child components, slots can be set to default values) V-slot :one parent component call slot defined in slot:<slot name="one"></slot>Scope slot:<div>
    <slot v-for="item in list" :item="item" />    
</div>

<list v-slot="props"> 
        <span>{{props.item}}</span> 
</list>Dynamic component definition: App.component.com ('dajiao', {template:`<img src="https://newimg.jspang.com/xiedajiao01.jpg" />`
})

app.component('liuying', {template:`<img src="https://newimg.jspang.com/liuying01.jpg" />`}) call < Component :is="showItem"/> Async component: app.component.ponent ('async-component',Vue.defineAsyncComponent(() = >{
    return new Promise((resolve,reject) = >{
        setTimeout(() = >{
            resolve({
                template:'
      
This is an asynchronous component
})},3000<p> <router-link to="/"> home page < / router - the link ><router-link to="/hi">Hi page</router-link></p> Child routing {path:'/hi'.component:Hi, children:[ {path:'/'.component:Hi}, {path:'hi1'.component:Hi1}, {path:'hi2'.component:Hi2}, ] } <router-link to="/"> home page < / router - the link > |<router-link to="/hi">Hi page</router-link> | <router-link to="/hi/hi1">Page 1 - Hi</router-link> | <router-link to="/hi/hi2">Page 2 - Hi</router-link>Router-link parameter transfer<router-link :to="{name:xxx,params:{key:value}}">valueString</router-link>{{$route.params.username}} <p>{{$route.name}}</p> </p><router-view name="left" style="float:left; width:50%; background-color:#ccc; height:300px;"></router-view> <router-view name="right" style="float:right; width:50%; background-color:#c0c; height:300px;"></router-view>Route definition: {path: '/'.components: { default:Hello, left:Hi1, right:Hi2}} Use url to pass parameters: {path:'/params/:newsId/:newsTitle'.component$router = $router = $router = $router<p>{{$route.params.newsId}}</p> <p>{{$route.params.newstitle}}</p>Router-link configuration:<router-link to="/params/198/jspang website is very good">params</router-link>Alias: route alias: {path: '/hi1'.component: Hi1, alias:'/jspang' } <router-link to="/jspang"> jspang < / router - the link > if the path is'/', is invalid {path: '/'.component: Hello, alias:'/home'} Route animation:<transition name="fade"> <router-view ></router-view> </transition>configuration404Page: {path:The '*'.component:Error} Route hook: write hook function in route configuration file (/ SRC /router/index.js). Write hook function in template: beforeRouteEnter: hook function before route entry. BeforeRouteLeave: The hook function before the route leaves. Programmatic navigation:this.$router.go(-1); Equivalent to goback router. Go (1(It stands for progressCopy the code