Vue.js--vue-router 60-minute Quick Start

Source: Internet
Author: User

Overview

Vue-router is Vue.js's official routing plugin, which is deeply integrated with vue.js and is ideal for building single-page applications. Vue's single-page applications are routing-and component-based, and routing is used to set access paths and map paths and components. Traditional page application, is to use some hyperlinks to achieve page switching and jump. In Vue-router single page application, it is the switch between the paths, that is, the switch of the components.

This article introduces the various features of vue-router in the form of an example, including 6 examples, each with a beggar version and the first 5 examples with the Emperor version.
The beggar version is an HTML page that mixes all the code together, and the emperor version is built based on the vue-webpack-simple template.

The beggar version allows you to quickly get to know some of the features and APIs of Vue-router, and the emperor version is based on the. Vue component and the separate routing configuration, which is more suitable for practical applications.

The demo and source code for this article has been put on GitHub, and if you think it's a good one, please click on it or add a star on GitHub!

First single-page application nested routines By example named path example p route Object example make link selected sample hook function sample GitHub Source

On GitHub, the directory structure of the beggar and yellow floors is as follows:

├─06. router//vue-router Sample Catalog │   ├─basic//Beggar version example │   ├──basic_01.html//first single page app │   ├──basic_02.html//nested routines by example │   ├──basic_03.html//named path example │   ├──basic_04.html//route object Instance │   ├──basic_05.html//Let link is selected example │   ├──basic_06. html//Hook Function Example │   ├─demo01//Emperor Edition, and basic_01.html correspondence │   ├─demo02//Emperor Edition, and basic_02.html correspondence │   ├─demo03//Emperor Edition, and basic _03.html corresponds   to │ ├─demo04//Emperor Edition, and basic_04.html corresponds to │   ├─demo05//Emperor Edition, and basic_05.html corresponds
First single page application (01)

Now we start the Vue-router tour with a simple single page app with two paths: /home and /about , the two paths correspond to the two components home and about.

1. Creating components

First introduce Vue.js and vue.js:

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

Then create two component constructors home and about:

var Home = vue.extend ({Template: ' <div>
2. Create Router
var router = new Vuerouter ()

Call the constructor vuerouter to create a router instance router.

3. Map routes
Router.map ({'/home ': {component:home}, '/about ': {component:about}})

Call router's Map method to map the route, each route in the form of Key-value, key is the path, and value is the component.
For example ‘/home‘ , a key for a route that represents a path, {component: Home} or a component that represents that route map.

4. Using the V-link directive
<div class= "List-group" ><a class= "List-group-item" v-link= "{path: '/Home '}" >home</a><a class= " List-group-item "v-link=" {path: '/about '} ' >About</a></div>

Use the instruction on the a element v-link to jump to the specified path.

5. Use <router-view> tags
<router-view></router-view>

Use a label on the page <router-view></router-view> that is used to render matching components.

6. Start the route
var app = Vue.extend ({}) Router.start (app, ' #app ')

The operation of the router requires a root component, which router.start(App, ‘#app‘) means that router creates an instance of the app and mounts it to the #app element.
Note: using Vue-router's app, you do not need to explicitly create a Vue instance, but instead call the Start method to mount the root component to an element.

View Demo

When you get the latest source code from GitHub, if you want to run the Emperor version, take demo01 as an example, execute the following command under GIT bash:

NPM Run Demo01-dev

Then access the address in the browser http://127.0.0.1:8080

If you want to compile and publish, execute the following command under GIT bash:

NPM Run Demo01-build
Steps to write a single page

The 6 steps above are the basic steps to create a single-page app:

Javascript
    1. Create a component: Create a component that needs to be rendered for a single page app
    2. Create a route: Create a Vuerouter instance
    3. Map route: Call the Map method of the Vuerouter instance
    4. Start route: Call the Start method of the Vuerouter instance
Html
    1. Using the V-link directive
    2. Use <router-view> tags
Router.redirect

The right side of the app is blank at first run, and the app usually has a home page, for example: home.
Use router.redirect the method to redirect the root path to the/home path:

Router.redirect ({'/': '/Home '})

router.redirectmethod is used to define a global redirection rule for the router, and global redirection is performed before the current path is matched.

Execution process

When the user clicks on the v-link instruction element, we can roughly guess what's going on in the middle:

    • Vue-router first goes to find v-link the route map of the instruction
    • The matching component is then found based on the route map
    • Finally render the component to the <router-view> label

Nested routines by (02)

Nested routines are a common requirement, assuming that the user is able to /home/news /home/message map a component by path and access to some content, and that accessing both paths will render two components respectively.

There are two key points to implementing a nested routine:

    • Using labels inside a component <router-view>
    • To define a sub-route to a component in a router object

Now we're going to do this.

Component templates:

<template id= "Home" ><div>

Component Builder:

var Home = vue.extend ({Template: ' #home ', data:function () {return {msg: ' Hello, Vue router! '}}}) var News = vue.extend ({Template: ' #news '}) var Message = vue.extend ({Template: ' #message '})

Route Map:

Router.map ({'/home ': {component:home,//defines sub-route subroutes: {'/news ': {component:news}, '/message ': {component:message}} }, '/about ': {component:about}})

/homea subroutes option is defined under routing, /news and /message is two sub-routes that represent the path /home/news and, respectively /home/message , the component news and message.

The example runs as follows:

View Demo

Note: Here is a concept to distinguish between, /home/news and /home/message is the Zi Lu of the route, and the /home corresponding news and message component is not a child component of home.

Named Path (03)

In some cases, adding a name to a path makes it easier for us to jump the path, especially if the path is longer.

We append one more component Newsdetail, which is rendered when accessing the/home/news/detail path, the component template:

<template id= "Newsdetail" ><div>news Detail-{{$route. params.id}} ......</div></template>

Component Builder:

var newsdetail = vue.extend ({Template: ' #newsDetail '})
Named Route mappings
Router.map ({'/home ': {component:home,subroutes: {'/news ': {name: ' News ', component:news,subroutes: {' Detail/:id ': { Name: ' Detail ', Component:newsdetail}}}, '/message ': {Component:message}}}, '/about ': {component:about}})

Note: /homes/news/ when defining and home/news/detail/:id routing, we specify properties for this route name .
/:idis a route parameter, for example: If you want to see the news details for id = ' 01 ', then the access path is/home/news/detail/01.

Home components and News component templates:

<template id= "Home" ><div >

<a v-link="{ name: ‘news‘}">News</a>And <a v-link="{ name: ‘detail‘, params: {id: ‘01‘} }">News 01</a> These two lines of HTML code are used with the named path.

The example runs as follows:

View Demo

V-link directive

It took so long to v-link the instructions, it was time to introduce it.

v-linkis an instruction to allow users to jump between different paths in a vue-router application. The directive accepts a JavaScript expression and invokes it with the value of the expression when the user taps the element router.go .

Specifically, there are three ways to use V-link:

<!--literal path--><a v-link= "' Home '" >Home</a><!--effect ditto--><a v-link= "{path: ' Home '}" >home </a><!--named path--><a v-link= "{name: ' detail ', params: {id: ' '}}" >Home</a>

v-linkAutomatically set <a> the href properties you don't need to use href to handle browser adjustments for the following reasons:

    • It works the same way in HTML5 history mode and in hash mode, so if you decide to change the pattern, or if the IE9 browser is degraded to hash mode, you don't need to make any changes.

    • In HTML5 history mode, the v-link Click event is monitored to prevent the browser from trying to reload the page.

    • When you use the option in HTML5 history mode root , you do not need to v-link include the root path in the URL.

Routing Objects (04)

In an application that uses Vue-router, the routing object is injected into each component, assigned to it, this.$route and the routing object is updated when the route is switched.

The following properties are exposed by the routing object:

    • $route. Path

      The string, which is equal to the path of the current route object, is resolved to an absolute path, such as "/foo/bar" .

    • $route. Params

      Object that contains the key value pairs for the dynamic fragment and the fully matched fragment in the route, as detailed in the following article

    • $route. Query

      Object that contains the key-value pairs for the query parameters in the route. For example, for /foo?user=1 , you will get $route.query.user == 1 .

    • $route. Router

      The router to which the routing rule belongs (and the component to which it belongs).

    • $route. Matched

      Array that contains the configuration parameter objects for all fragments contained in the currently matched path.

    • $route. Name

      The name of the current path.

Add the following code on the page to display the properties of these routing objects:

<div><p> Current path: {{$route .path}}</p><p> current parameter: {{$route. params | json}}</p><p> route name: {{$route .name}}</p><p> route query parameter: {{$route. query | json}}</p><p> route match: {{$route. matched | json}} </p></div>

$route.path, $route.params, $route.name, $route.queryThese properties are easy to understand and can be seen in the example to see what they mean.

(Because the $route.matched content is longer, so it is not displayed on the screen)

Here I want to say a little bit about the $router.matched property, which is an inclusive match that matches the parent route that nested it.

For example, /home/news/detail/:id this path, which contains 3 matching routes:

    1. /home/news/detail/:id
    2. /home/news
    3. /home

In addition, the element with the v-link directive, if the v-link corresponding URL matches the current path, the element will be added to the specific class, the default name of the class v-link-active . For example, when we access /home/news/detail/03 this URL, according to the matching rules, there will be 3 links are added v-link-active .

View Demo

Keep links Active (05)

There are two problems with the above picture:

    1. When the user clicks the home link or the About link, the link does not appear to be selected
    2. When the user clicks the news or message link, the link does not appear to be selected
Set Activeclass

The 1th problem can be solved by setting v-link instructions activeClass .

<a class= "List-group-item" v-link= "{path: ' Home ', Activeclass: ' Active '}" >home</a><a class= " List-group-item "v-link=" {path: '/about ', Activeclass: ' Active '} ' >About</a>

After setting the v-link Activeclass property of the instruction, the default v-link-active is replaced by the new class.

2nd question, setting Activeclass for the V-link directive is not working because we are using the bootstrap style and need to set the parent element of the a tag <li> to make the link appear to be selected, as shown in the following code:

<ul class= "Nav nav-tabs" ><li class= "active" ><a v-link= "{path: '/home/news '}" >news</a></ Li><li><a v-link= "{path: '/home/message '}" >Messages</a></li></ul>

How do you achieve this effect? You might think of appending a Currentpath property to the data option of the home component, and then binding class using the following method.

<ul class= "nav nav-tabs" ><li:class= "currentpath = = '/home/news '? ' Active ': ' ><a v-link= ' {path: '/home/news '} ' >news</a></li><li:class= ' Currentpath = = '/ Home/message '? ' Active ': ' "><a v-link=" {path: '/home/message '} ' >Messages</a></li></ul>

Now another question arises, under what circumstances should the Currentpath be assigned?

When the user taps the V-link element, it is the routing switch.
Each component has a route option, and the route option has a series of hook functions that perform these hooks when switching routes.
One of the hook functions is the data hook function, which is used to load and set up the components.

var Home = vue.extend ({Template: ' #home ', data:function () {return {msg: ' Hello, Vue router! ', Currentpath: '}},route: {dat A:function (Transition) {Transition.next ({CurrentPath:transition.to.path})}})

The example works as follows:

View Demo

hook function (06)

The routing process is essentially a series of routing hooks, and the hook functions are generally divided into two broad categories:

    • Global hook function
    • The hook function of the component

The global hook function is defined in the global routing object, and the component's hook function is defined in the component's route options.

Global hook function

There are 2 global hook functions:

    • beforeEach: Called when the routing switch starts
    • afterEach: Called when each route switch successfully enters the activation phase
The hook function of the component

The hook function for the components is 6 total:

    • Data: You can set the data of the component
    • Activate: Activating components
    • Deactivate: Disabling components
    • Canactivate: Whether the component can be activated
    • Candeactivate: Whether the component can be disabled
    • Canreuse: Whether a component can be reused
Toggle Object

Each toggle hook function will accept an transition object as a parameter. This toggle object contains the following functions and methods:

    • transition.to

      A route object that represents the path to which the switch will be switched.

    • Transition.from

      The route object that represents the current path.

    • Transition.next ()

      Call this function to handle the next step of the switchover process.

    • Transition.abort ([reason])

      Call this function to terminate or reject this switch.

    • transition.redirect (path)

      Cancels the current switch and redirects to another route.

Order of execution of the hook function

The global hook function and the component hook function add up to a total of 8, in order to skillfully use the Vue router, it is necessary to understand the order of execution of these hooks functions.

To visually understand the order of execution of these hook functions, append a Vue instance to the screen:

var well = new Vue ({el: '. Well ', data: {msg: ', color: ' #ff0000 '},methods: {setcolor:function () {this.color = ' # ' + Parsein T (Math.random () *256). ToString (+) + parseint (Math.random () *256). ToString (+) + parseint (Math.random () *256). ToString (+)},setcoloredmessage:function (msg) {this.msg + =  ' <p style= ' color: ' + this.color + ' "> ' + msg + ' < /p> '},settitle:function (title) {this.msg =  ' 

The HTML for the well instance:

<div class= "Well" >{{{msg}}}</div>

Then, add a routehelper function that records the execution log for each hook function:

function Routehelper (name) {var route = {Canreuse:function (transition) {well.setcoloredmessage (' actor ' + name + ' hook function: CA Nreuse ') return True},canactivate:function (transition) {well.setcoloredmessage (' actor ' + name + ' hook function: Canactivate ') Transition.next ()},activate:function (transition) {well.setcoloredmessage (' Execute component ' + name + ' hook function: Activate ') Transition.next ()},candeactivate:function (transition) {well.setcoloredmessage (' actor ' + name + ' hook function: Candeactivate ' ) Transition.next ()},deactivate:function (transition) {well.setcoloredmessage (' actor ' + name + ' hook function: Deactivate ') Transition.next ()},data:function (transition) {well.setcoloredmessage (' Execute component ' + name + ' hook function: Data ') Transition.next () }}return Route;}

Finally, apply these hook functions to each component:

var Home = vue.extend ({Template: ' #home ', data:function () {return {msg: ' Hello, Vue router! ', Path: '}},route:routehelper (' Home ')}) var News = vue.extend ({Template: ' #news ', Route:routehelper (' News ')}) var Message = vue.extend ({Template: ' #message ', Route:routehelper (' Message ')}) var = vue.extend ({Template: ' #about ', Route:routehelper (' About ')})

Let's do a little experiment by following these steps:

    1. Run the app (Access /home path)
    2. Access /home/news Path
    3. Access /home/message Path
    4. Access /about Path

View Demo

Switching control lines

What did Vue-router do when the user clicked on the/home/news link and then clicked the/home/message link? It executes a switch pipeline.

How do we do that? This process contains some of the work we have to do:

    1. Component home can be reused because the component home remains intact after re-rendering.

    2. You need to deactivate and remove the component news.

    3. Enables and activates the component message.

    4. Before you perform steps 2 and 3, you need to ensure that the switching effect is valid-that is, to ensure that all components involved in the switchover are deactivated/activated as expected.

Each phase of the switchover

We can divide the switching of routes into three phases: the reusable phase, the validation phase, and the activation phase.

Let's take a home/news switch to home/message The example to describe each stage.
(Refer to the following text description: http://router.vuejs.org/zh-cn/pipeline/index.html)

1. Reusable Stages

Checks whether there are components that can be reused in the current view structure. This is done by comparing two new component trees, finding common components, and then checking their reusability (through canReuse options). By default, all components are reusable, unless they are custom-made.

2. Verification phase

Checks whether the current component can be deactivated and whether the new component can be activated. This is determined by invoking the routing configuration phase canDeactivate and the canActivate hook function.

3. Activation phase

Once all the validation hooks have been called and the switch is not terminated, the switchover can be considered legitimate. The router starts disabling the current component and enabling the new component.

This phase corresponds to the invocation order of the hook function and the validation phase, which is intended to provide an opportunity to clean up and prepare before the component switch is actually executed. Updates to the interface will wait until all the affected components are deactivate executed and the activate hooks function executes.

dataThis hook function will be called activate later, or it will be called when the current component component can be reused. Summarize

This article mainly introduces the following content:

    • Describe the basic steps for writing a single page application
    • Introduces nested routines by
    • Introducing named Paths
    • Introducing Routing Objects
    • Describes hook functions and execution order
    • Introduction to component switching control pipeline

Vue.js--vue-router 60-minute Quick Start

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.