Home > Web Front-end > JS Tutorial > body text

Analysis on the use of vue routing

不言
Release: 2018-06-29 11:44:03
Original
1868 people have browsed it

This article mainly introduces the usage analysis of vue routing, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

vue-router is the official routing of Vue.js Plug-in, which is deeply integrated with vue.js and suitable for building single-page applications.

vue-router is the official routing plug-in of Vue.js. It is deeply integrated with vue.js and is suitable for building single-page applications. Vue's single-page application is based on routing and components. Routing is used to set access paths and map paths and components. Traditional page applications use some hyperlinks to achieve page switching and jumps. In the vue-router single-page application, it is switching between paths, that is, switching of components.

This article will introduce various features of vue-router in the form of examples. It contains 6 examples in total. Each example has a beggar version, and the first 5 examples have an emperor version.
The beggar version is an HTML page with all the code mixed together, and the emperor version is built based on the vue-webpack-simple template.

The first single-page application (01)

Now we start the vue-router journey with a simple single-page application. This single-page application has two Paths: /home and /about. Corresponding to these two paths are the two components Home and About.

#1. Create components

First introduce vue.js and vue-router.js:

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

然后创建两个组件构造器Home和About:
var Home = Vue.extend({
 template: &#39;<p><h1>Home</h1><p>{{msg}}</p></p>&#39;,
 data: function() {
 return {
  msg: &#39;Hello, vue router!&#39;
 }
 }
})

var About = Vue.extend({
 template: &#39;<p><h1>About</h1><p>This is the tutorial about vue-router.</p></p>&#39;
})
Copy after login

2. Create Router

var router = new VueRouter()
Copy after login

Call the constructor VueRouter to create a router instance router.

3. Mapping routes

router.map({
 &#39;/home&#39;: { component: Home },
 &#39;/about&#39;: { component: About }
})
Copy after login

Call the map method of router to map routes. Each route exists in the form of key-value, where key is the path and value is the component.

For example: '/home' is the key of a route, which represents the path; {component: Home} represents the component mapped by the route.

4. Use the v-link instruction

<p class="list-group">
 <a class="list-group-item" v-link="{ path: &#39;/home&#39;}">Home</a>
 <a class="list-group-item" v-link="{ path: &#39;/about&#39;}">About</a>
</p>
Copy after login

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

5. Use the tag

<router-view></router-view>
Copy after login

Use the <router-view></router-view> tag on the page, which uses for rendering matching components.

6. Start routing

var App = Vue.extend({})
router.start(App, &#39;#app&#39;)
Copy after login

The operation of the router requires a root component. router.start(App, '#app') means that the router will create an App instance. And mounted to the #app element.

Note: Applications using vue-router do not need to explicitly create a Vue instance. Instead, call the start method to mount the root component to an element.

After you obtain the latest source code from GitHub, if you want to run the Emperor Edition, take demo01 as an example and execute the following command under Git Bash:

npm run demo01-dev
Copy after login

Then visit the address http://127.0.0.1:8080

in the browser. If you want to compile and publish, please execute the following command under Git Bash:

npm run demo01-build
Copy after login

Steps to write a single page

The above 6 steps can be said to be the basic steps for creating a single page application:

JavaScript

1. Create components: Create components that need to be rendered by single-page applications

2. Create routes: Create a VueRouter instance

3. Map routing: call the map method of the VueRouter instance

4. Start routing: call the start method of the VueRouter instance

HTML

##1. Use the v-link directive


2. Use the tag

router.redirect

When the application is run for the first time, the right side is blank. The application usually has a home page, such as the Home page.


Use the router.redirect method to redirect the root path to the /home path:

router.redirect({
 &#39;/&#39;: &#39;/home&#39;
})
Copy after login

The router.redirect method is used to define global redirection rules for the router, global redirection Will be executed before matching the current path.

Execution process

When the user clicks on the v-link instruction element, we can roughly guess what happened:

  1. vue-router will first look for the routing mapping of the v-link directive

  2. and then find the matching component based on the routing mapping

  3. Finally, render the component to the tag

##Nested routing (02)

Nested routing is a common requirement. Assume that users can access some content through the paths /home/news and /home/message. One path maps a component, and accessing these two paths will also render two components respectively.

There are two key points to implement nested routing:

    Use the tag inside the component
  1. 在路由器对象中给组件定义子路由

现在我们就动手实现这个需求。

组件模板:




Copy after login

组件构造器:

var Home = Vue.extend({
 template: &#39;#home&#39;,
 data: function() {
 return {
  msg: &#39;Hello, vue router!&#39;
 }
 }
})

var News = Vue.extend({
 template: &#39;#news&#39;
})

var Message = Vue.extend({
 template: &#39;#message&#39;
})
Copy after login

路由映射:

router.map({
 &#39;/home&#39;: {
 component: Home,
 // 定义子路由
 subRoutes: {
  &#39;/news&#39;: {
  component: News
  },
  &#39;/message&#39;: {
  component: Message
  }
 }
 },
 &#39;/about&#39;: {
 component: About
 }
})
Copy after login

在/home路由下定义了一个subRoutes选项,/news和/message是两条子路由,它们分别表示路径/home/news和/home/message,这两条路由分别映射组件News和Message。

该示例运行如下:

注意:这里有一个概念要区分一下,/home/news和/home/message是/home路由的子路由,与之对应的News和Message组件并不是Home的子组件。

具名路径(03)

在有些情况下,给一条路径加上一个名字能够让我们更方便地进行路径的跳转,尤其是在路径较长的时候。

我们再追加一个组件NewsDetail,该组件在访问/home/news/detail路径时被渲染,组件模板:

<template id="newsDetail">
 <p>
 News Detail - {{$route.params.id}} ......
 </p>
</template>
Copy after login

组件构造器:

var NewsDetail = Vue.extend({
 template: &#39;#newsDetail&#39;
})
Copy after login

具名路由映射

router.map({
 &#39;/home&#39;: {
 component: Home,
 subRoutes: {
  &#39;/news&#39;: {
  name: &#39;news&#39;,
  component: News,
  subRoutes: {
   &#39;detail/:id&#39;: {
   name: &#39;detail&#39;,
   component: NewsDetail
   }
  }
  },
  &#39;/message&#39;: {
  component: Message
  }
 }
 },
 &#39;/about&#39;: {
 component: About
 }
})
Copy after login

注意:我们在定义/homes/news/和home/news/detail/:id路由时,给该路由指定了name属性。

/:id是路由参数,例如:如果要查看id = '01'的News详情,那么访问路径是/home/news/detail/01。

Home组件和News组件模板:

Copy after login
Copy after login

NewsNews 01这两行HTML代码,使用了用了具名路径。

该示例运行如下:

v-link指令

用了这么久的v-link指令,是该介绍一下它了。

v-link 是一个用来让用户在 vue-router 应用的不同路径间跳转的指令。该指令接受一个 JavaScript 表达式,并会在用户点击元素时用该表达式的值去调用 router.Go。

具体来讲,v-link有三种用法:

<!-- 字面量路径 -->
<a v-link="&#39;home&#39;">Home</a>

<!-- 效果同上 -->
<a v-link="{ path: &#39;home&#39; }">Home</a>

<!-- 具名路径 -->
<a v-link="{ name: &#39;detail&#39;, params: {id: &#39;01&#39;} }">Home</a>
Copy after login

v-link 会自动设置 的 href 属性,你无需使用href来处理浏览器的调整,原因如下:

它在 HTML5 history 模式和 hash 模式下的工作方式相同,所以如果你决定改变模式,或者 IE9 浏览器退化为 hash 模式时,都不需要做任何改变。

在 HTML5 history 模式下,v-link 会监听点击事件,防止浏览器尝试重新加载页面。

在 HTML5 history 模式下使用 root 选项时,不需要在 v-link 的 URL 中包含 root 路径。

路由对象(04)

在使用了 vue-router 的应用中,路由对象会被注入每个组件中,赋值为 this.$route ,并且当路由切换时,路由对象会被更新。

路由对象暴露了以下属性:

$route.path

字符串,等于当前路由对象的路径,会被解析为绝对路径,如 "/home/news" 。

$route.params

对象,包含路由中的动态片段和全匹配片段的键值对

$route.query

对象,包含路由中查询参数的键值对。例如,对于 /home/news/detail/01?favorite=yes ,会得到$route.query.favorite == 'yes' 。

$route.router

路由规则所属的路由器(以及其所属的组件)。

$route.matched

数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。

$route.name

当前路径的名字,如果没有使用具名路径,则名字为空。

在页面上添加以下代码,可以显示这些路由对象的属性:

$route.path, $route.params, $route.name, $route.query这几个属性很容易理解,看示例就能知道它们代表的含义。

(由于$route.matched内容较长,所以没有将其显示在画面上)

这里我要稍微说一下$router.matched属性,它是一个包含性的匹配,它会将嵌套它的父路由都匹配出来。

例如,/home/news/detail/:id这条路径,它包含3条匹配的路由:

1./home/news/detail/:id

2./home/news

3./home

另外,带有 v-link 指令的元素,如果 v-link 对应的 URL 匹配当前的路径,该元素会被添加特定的class,该class的默认名称为v-link-active。例如,当我们访问/home/news/detail/03这个URL时,根据匹配规则,会有3个链接被添加v-link-active。

让链接处于活跃状态(05)

以上画面存在两个问题:

1.当用户点击Home链接或About链接后,链接没有显示为选中

2.当用户点击News或Message链接后,链接没有显示为选中

设置activeClass

第1个问题,可以通过设定v-link指令的activeClass解决。

设定了v-link指令的activeClass属性后,默认的v-link-active被新的class取代。

第2个问题,为v-link指令设定activeClass是不起作用的,因为我们使用的是bootstrap的样式,需要设置a标签的父元素

  • 才能让链接看起来处于选中状态,就像下面的代码所展现的:

    <ul class="nav nav-tabs">
     <li class="active">
     <a v-link="{ path: &#39;/home/news&#39;}">News</a>
     </li>
     <li>
     <a v-link="{ path: &#39;/home/message&#39;}">Messages</a>
     </li>
    </ul>
    Copy after login

    如何实现这个效果呢?你可能会想到,为Home组件的data选项追加一个currentPath属性,然后使用以下方式绑定class。

    <ul class="nav nav-tabs">
     <li :class="currentPath == &#39;/home/news&#39; ? &#39;active&#39;: &#39;&#39;">
     <a v-link="{ path: &#39;/home/news&#39;}">News</a>
     </li>
     <li :class="currentPath == &#39;/home/message&#39; ? &#39;active&#39;: &#39;&#39;">
     <a v-link="{ path: &#39;/home/message&#39;}">Messages</a>
     </li>
    </ul>
    Copy after login

    现在又出现了另一个问题,在什么情况下给currentPath赋值呢?

    用户点击v-link的元素时,是路由的切换。

    每个组件都有一个route选项,route选项有一系列钩子函数,在切换路由时会执行这些钩子函数。

    其中一个钩子函数是data钩子函数,它用于加载和设置组件的数据。

    var Home = Vue.extend({
     template: &#39;#home&#39;,
     data: function() {
     return {
      msg: &#39;Hello, vue router!&#39;,
      currentPath: &#39;&#39;
     }
     },
     route: {
     data: function(transition){
      transition.next({
      currentPath: transition.to.path
      })
     }
     }
    })
    Copy after login

    该示例运行效果如下:

    钩子函数(06)

    路由的切换过程,本质上是执行一系列路由钩子函数,钩子函数总体上分为两大类:

    1. 全局的钩子函数

    2. 组件的钩子函数

    全局的钩子函数定义在全局的路由对象中,组件的钩子函数则定义在组件的route选项中。

    全局钩子函数

    全局钩子函数有2个:

    1. beforeEach:在路由切换开始时调用

    2. afterEach:在每次路由切换成功进入激活阶段时被调用

    组件的钩子函数

    组件的钩子函数一共6个:

    1. data:可以设置组件的data

    2. activate:激活组件

    3. deactivate:禁用组件

    4. canActivate:组件是否可以被激活

    5. canDeactivate:组件是否可以被禁用

    6. canReuse:组件是否可以被重用

    切换对象

    每个切换钩子函数都会接受一个 transition 对象作为参数。这个切换对象包含以下函数和方法:

    transition.to

    表示将要切换到的路径的路由对象。

    transition.from

    代表当前路径的路由对象。

    transition.next()

    调用此函数处理切换过程的下一步。

    transition.abort([reason])

    调用此函数来终止或者拒绝此次切换。

    transition.redirect(path)

    取消当前切换并重定向到另一个路由。

    钩子函数的执行顺序

    全局钩子函数和组件钩子函数加起来一共8个,为了熟练vue router的使用,有必要了解这些钩子函数的执行顺序。

    为了直观地了解这些钩子函数的执行顺序,在画面上追加一个Vue实例:

    var well = new Vue({
     el: &#39;.well&#39;,
     data: {
     msg: &#39;&#39;,
     color: &#39;#ff0000&#39;
     },
     methods: {
     setColor: function(){
      this.color = &#39;#&#39; + parseInt(Math.random()*256).toString(16)
       + parseInt(Math.random()*256).toString(16)
       + parseInt(Math.random()*256).toString(16)
     },
     setColoredMessage: function(msg){
      this.msg += &#39;<p style="color: &#39; + this.color + &#39;">&#39; + msg + &#39;</p>&#39;
     },
     setTitle: function(title){
      this.msg = &#39;<h2 style="color: #333">&#39; + title + &#39;</h2>&#39;
     }
     }
    })
    Copy after login

    well实例的HTML:

    <p class="well">
     {{{ msg }}}
    </p>
    Copy after login

    然后,添加一个RouteHelper函数,用于记录各个钩子函数的执行日志:

    function RouteHelper(name) {
     var route = {
     canReuse: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:canReuse&#39;)
      return true
     },
     canActivate: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:canActivate&#39;)
      transition.next()
     },
     activate: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:activate&#39;)
      transition.next()
     },
     canDeactivate: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:canDeactivate&#39;)
      transition.next()
     },
     deactivate: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:deactivate&#39;)
      transition.next()
     },
     data: function(transition) {
      well.setColoredMessage(&#39;执行组件&#39; + name + &#39;的钩子函数:data&#39;)
      transition.next()
     }
     }
     return route;
    }
    Copy after login

    最后,将这些钩子函数应用于各个组件:

    var Home = Vue.extend({
     template: &#39;#home&#39;,
     data: function() {
     return {
      msg: &#39;Hello, vue router!&#39;,
      path: &#39;&#39;
     }
     },
     route: RouteHelper(&#39;Home&#39;)
    })
    
    var News = Vue.extend({
     template: &#39;#news&#39;,
     route: RouteHelper(&#39;News&#39;)
    })
    
    var Message = Vue.extend({
     template: &#39;#message&#39;,
     route: RouteHelper(&#39;Message&#39;)
    })
    
    var About = Vue.extend({
     template: &#39;#about&#39;,
     route: RouteHelper(&#39;About&#39;)
    })
    Copy after login

    我们按照以下步骤做个小实验:

    1.运行应用(访问/home路径)

    2.访问/home/news路径

    3.访问/home/message路径

    4.访问/about路径

     切换控制流水线

    当用户点击了/home/news链接,然后再点击/home/message链接后,vue-router做了什么事情呢?它执行了一个切换管道

    如何做到这些呢?这个过程包含一些我们必须要做的工作:

    1.可以重用组件Home,因为重新渲染后,组件Home依然保持不变。

    2.需要停用并移除组件News。

    3.启用并激活组件Message。

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

    Various stages of switching

    We can divide routing switching into three stages: reusable stage, verification stage and activation stage.

    We take switching from home/news to home/message as an example to describe each stage. (Refer to the following text description: http://router.vuejs.org/zh-cn/pipeline/index.html)

    1. Reusable phase

    Check Whether there are reusable components in the current view structure. This is done by comparing the two new component trees, identifying shared components, and then checking their reusability (via the canReuse option). By default, all components are reusable unless customized.

    2. Verification phase

    Check whether the current component can be deactivated and whether the new component can be activated. This is judged by calling the canDeactivate and canActivate hook functions in the routing configuration phase.

    3. Activation phase

    Once all verification hook functions are called and the switch is not terminated, the switch can be considered to be legal. The router then begins disabling current components and enabling new components.

    The calling sequence of the corresponding hook function in this phase is the same as that in the verification phase. Its purpose is to provide an opportunity for cleaning and preparation before component switching is actually executed. The interface is updated until the deactivate and activate hook functions of all affected components are executed.

    data This hook function will be called after activate, or when the current component component can be reused.

    The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

    Related recommendations:

    vue.extend implements alert modal box pop-up component

    About how vue introduces sass global Analysis of variables

    #How to solve the problem that the page is blank after the routing History mode is packaged under Vue

    The above is the detailed content of Analysis on the use of vue routing. For more information, please follow other related articles on the PHP Chinese website!

  • Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!