vue-vue router link tov-link 带查询参数怎么写

7867人阅读
1.路径:http://localhost:8081/#/test?name=1
&router-link :to=&{path:'/test',query: {name: id}}&&跳转&/router-link&(id是参数)
使用:this.$route.query.id
2.路径:http://localhost:8081/#/test/1
&router-link :to=&'/test/'+id&&跳转&/router-link&(id是参数)
使用:this.$route.params.id(这个id给上图路由的配置有关)
this.$route是一个数组,里面包含路由的所有信息
注意:router-link中链接如果是‘/’开始就是从根路由开始,如果开始不带‘/’,则从当前路由开始
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:57391次
积分:1138
积分:1138
排名:千里之外
原创:52篇
评论:11条
(1)(1)(1)(22)(9)(6)(1)(2)(4)(6)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'自由、创新、研究、探索
Linux/Windows Mono/DotNet [ Open Source .NET Development/ 使用开源工具进行DotNet软件开发]锐意进取,志存高远.成就梦想,只争朝夕.从你开始,创新世界.【That I exist is a perpetual supprise which is life. Focus on eCommerce】
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
本文将以示例的形式来介绍vue-router的各个特性,一共包含6个示例,每个示例都有乞丐版,前5个示例有皇帝版。乞丐版是将所有代码混杂在一起的HTML页面,皇帝版是基于vue-webpack-simple模板构建的。
乞丐版可以让你快速地了解到vue-router的一些特性和API;皇帝版则基于.vue组件和单独的路由配置,更适用于实际的应用。
本文的Demo和源代码已放到GitHub,如果您觉得内容不错,请点个赞,或在GitHub上加个星星!
在GitHub上,乞丐版和皇帝版的目录结构如下:
├─06.Router
// vue-router示例目录
// 乞丐版示例
├──basic_01.html // 第一个单页面应用
├──basic_02.html // 嵌套路由示例
├──basic_03.html // 具名路径示例
├──basic_04.html // 路由对象实例
├──basic_05.html // 让链接处于选中状态示例
├──basic_06.html // 钩子函数示例
├─demo01
// 皇帝版,和basic_01.html对应
├─demo02
// 皇帝版,和basic_02.html对应
├─demo03
// 皇帝版,和basic_03.html对应
├─demo04
// 皇帝版,和basic_04.html对应
├─demo05
// 皇帝版,和basic_05.html对应
第一个单页面应用(01)
现在我们以一个简单的单页面应用开启vue-router之旅,这个单页面应用有两个路径:/home和/about,与这两个路径对应的是两个组件Home和About。
1. 创建组件
首先引入vue.js和vue-router.js:
&script src="js/vue.js"&
然后创建两个组件构造器Home和About:
var Home = Vue.extend({
template: '&div&&h1&Home&/h1&&p&{{msg}}&/p&&/div&',
data: function() {
msg: 'Hello, vue router!'
var About = Vue.extend({
template: '&div&&h1&About&/h1&&p&This is the tutorial about vue-router.&/p&&/div&'
2. 创建Router
var router = new VueRouter()
调用构造器VueRouter,创建一个路由器实例router。
3. 映射路由
router.map({
'/home': { component: Home },
'/about': { component: About }
调用router的map方法映射路由,每条路由以key-value的形式存在,key是路径,value是组件。例如:'/home'是一条路由的key,它表示路径;{component: Home}则表示该条路由映射的组件。
4. 使用v-link指令
&div class="list-group"&
在a元素上使用v-link指令跳转到指定路径。
5. 使用&router-view&标签
在页面上使用&router-view&&/router-view&标签,它用于渲染匹配的组件。
6. 启动路由
var App = Vue.extend({})
router.start(App, '#app')
路由器的运行需要一个根组件,router.start(App, '#app')&表示router会创建一个App实例,并且挂载到#app元素。注意:使用vue-router的应用,不需要显式地创建Vue实例,而是调用start方法将根组件挂载到某个元素。
当你从GitHub上获取到最新的源代码后,如果想运行皇帝版,以demo01为例,在Git Bash下执行以下命令:
npm run demo01-dev
然后在浏览器中访问地址
如果要编译和发布,请在Git Bash下执行以下命令:
npm run demo01-build
编写单页面的步骤
上面的6个步骤,可以说是创建一个单页面应用的基本步骤:
JavaScript
创建组件:创建单页面应用需要渲染的组件
创建路由:创建VueRouter实例
映射路由:调用VueRouter实例的map方法
启动路由:调用VueRouter实例的start方法
使用v-link指令
使用&router-view&标签
router.redirect
应用在首次运行时右侧是一片空白,应用通常都会有一个首页,例如:Home页。使用router.redirect方法将根路径重定向到/home路径:
router.redirect({
'/': '/home'
router.redirect方法用于为路由器定义全局的重定向规则,全局的重定向会在匹配当前路径之前执行。
当用户点击v-link指令元素时,我们可以大致猜想一下这中间发生了什么事情:
vue-router首先会去查找v-link指令的路由映射
然后根据路由映射找到匹配的组件
最后将组件渲染到&router-view&标签
嵌套路由(02)
嵌套路由是个常见的需求,假设用户能够通过路径/home/news和/home/message访问一些内容,一个路径映射一个组件,访问这两个路径也会分别渲染两个组件。
实现嵌套路由有两个要点:
在组件内部使用&router-view&标签
在路由器对象中给组件定义子路由
现在我们就动手实现这个需求。
组件模板:
组件构造器:
var Home = Vue.extend({
template: '#home',
data: function() {
msg: 'Hello, vue router!'
var News = Vue.extend({
template: '#news'
var Message = Vue.extend({
template: '#message'
路由映射:
router.map({
'/home': {
component: Home,
在/home路由下定义了一个subRoutes选项,/news和/message是两条子路由,它们分别表示路径/home/news和/home/message,这两条路由分别映射组件News和Message。
该示例运行如下:
注意:这里有一个概念要区分一下,/home/news和/home/message是/home路由的子路由,与之对应的News和Message组件并不是Home的子组件。
具名路径(03)
在有些情况下,给一条路径加上一个名字能够让我们更方便地进行路径的跳转,尤其是在路径较长的时候。
我们再追加一个组件NewsDetail,该组件在访问/home/news/detail路径时被渲染,组件模板:
组件构造器:
var NewsDetail = Vue.extend({
template: '#newsDetail'
具名路由映射
router.map({
'/home': {
component: Home,
subRoutes: {
'/news': {
name: 'news',
component: News,
subRoutes: {
'detail/:id': {
name: 'detail',
component: NewsDetail
'/message': {
component: Message
'/about': {
component: About
注意:我们在定义/homes/news/和home/news/detail/:id路由时,给该路由指定了name属性。/:id是路由参数,例如:如果要查看id = '01'的News详情,那么访问路径是/home/news/detail/01。
Home组件和News组件模板:
&a v-link="{ name: 'news'}"&News&/a&和&a v-link="{ name: 'detail', params: {id: '01'} }"&News 01&/a&这两行HTML代码,使用了用了具名路径。
该示例运行如下:
v-link指令
用了这么久的v-link指令,是该介绍一下它了。
v-link&是一个用来让用户在 vue-router 应用的不同路径间跳转的指令。该指令接受一个 JavaScript 表达式,并会在用户点击元素时用该表达式的值去调用&router.go。
具体来讲,v-link有三种用法:
v-link&会自动设置&&a&&的&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条匹配的路由:
/home/news/detail/:id
/home/news
另外,带有&v-link&指令的元素,如果&v-link&对应的 URL 匹配当前的路径,该元素会被添加特定的class,该class的默认名称为v-link-active。例如,当我们访问/home/news/detail/03这个URL时,根据匹配规则,会有3个链接被添加v-link-active。
让链接处于活跃状态(05)
以上画面存在两个问题:
当用户点击Home链接或About链接后,链接没有显示为选中
当用户点击News或Message链接后,链接没有显示为选中
设置activeClass
第1个问题,可以通过设定v-link指令的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&
设定了v-link指令的activeClass属性后,默认的v-link-active被新的class取代。
第2个问题,为v-link指令设定activeClass是不起作用的,因为我们使用的是bootstrap的样式,需要设置a标签的父元素&li&才能让链接看起来处于选中状态,就像下面的代码所展现的:
如何实现这个效果呢?你可能会想到,为Home组件的data选项追加一个currentPath属性,然后使用以下方式绑定class。
现在又出现了另一个问题,在什么情况下给currentPath赋值呢?
用户点击v-link的元素时,是路由的切换。每个组件都有一个route选项,route选项有一系列钩子函数,在切换路由时会执行这些钩子函数。其中一个钩子函数是data钩子函数,它用于加载和设置组件的数据。
var Home = Vue.extend({
template: '#home',
data: function() {
msg: 'Hello, vue router!',
currentPath: ''
data: function(transition){
transition.next({
currentPath: transition.to.path
该示例运行效果如下:
钩子函数(06)
路由的切换过程,本质上是执行一系列路由钩子函数,钩子函数总体上分为两大类:
全局的钩子函数
组件的钩子函数
全局的钩子函数定义在全局的路由对象中,组件的钩子函数则定义在组件的route选项中。
全局钩子函数
全局钩子函数有2个:
beforeEach:在路由切换开始时调用
afterEach:在每次路由切换成功进入激活阶段时被调用
组件的钩子函数
组件的钩子函数一共6个:
data:可以设置组件的data
activate:激活组件
deactivate:禁用组件
canActivate:组件是否可以被激活
canDeactivate:组件是否可以被禁用
canReuse:组件是否可以被重用
每个切换钩子函数都会接受一个&transition&对象作为参数。这个切换对象包含以下函数和方法:
transition.to&表示将要切换到的路径的。
transition.from&代表当前路径的路由对象。
transition.next()&调用此函数处理切换过程的下一步。
transition.abort([reason])&调用此函数来终止或者拒绝此次切换。
transition.redirect(path)&取消当前切换并重定向到另一个路由。
钩子函数的执行顺序
全局钩子函数和组件钩子函数加起来一共8个,为了熟练vue router的使用,有必要了解这些钩子函数的执行顺序。
为了直观地了解这些钩子函数的执行顺序,在画面上追加一个Vue实例:
var well = new Vue({
el: '.well',
color: '#ff0000'
methods: {
setColor: function(){
this.color = '#' + parseInt(Math.random()*256).toString(16)
+ parseInt(Math.random()*256).toString(16)
+ parseInt(Math.random()*256).toString(16)
setColoredMessage: function(msg){
this.msg +=
'&p style="color: ' + this.color + '"&' + msg + '&/p&'
setTitle: function(title){
this.msg =
'&h2 style="color: #333"&' + title + '&/h2&'
well实例的HTML:
然后,添加一个RouteHelper函数,用于记录各个钩子函数的执行日志:
function RouteHelper(name) {
var route = {
canReuse: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:canReuse')
return true
canActivate: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:canActivate')
transition.next()
activate: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:activate')
transition.next()
canDeactivate: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:canDeactivate')
transition.next()
deactivate: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:deactivate')
transition.next()
data: function(transition) {
well.setColoredMessage('执行组件' + name + '的钩子函数:data')
transition.next()
最后,将这些钩子函数应用于各个组件:
var Home = Vue.extend({
template: '#home',
data: function() {
msg: 'Hello, vue router!',
route: RouteHelper('Home')
var News = Vue.extend({
template: '#news',
route: RouteHelper('News')
var Message = Vue.extend({
template: '#message',
route: RouteHelper('Message')
var About = Vue.extend({
template: '#about',
route: RouteHelper('About')
我们按照以下步骤做个小实验:
运行应用(访问/home路径)
访问/home/news路径
访问/home/message路径
访问/about路径
切换控制流水线
当用户点击了/home/news链接,然后再点击/home/message链接后,vue-router做了什么事情呢?它执行了一个切换管道
如何做到这些呢?这个过程包含一些我们必须要做的工作:
可以重用组件Home,因为重新渲染后,组件Home依然保持不变。
需要停用并移除组件News。
启用并激活组件Message。
在执行步骤2和3之前,需要确保切换效果有效&&也就是说,为保证切换中涉及的所有组件都能按照期望的那样被停用/激活。
切换的各个阶段
我们可以把路由的切换分为三个阶段:可重用阶段,验证阶段和激活阶段。
我们以home/news切换到home/message为例来描述各个阶段。(以下文字描述参考:)
1. 可重用阶段
检查当前的视图结构中是否存在可以重用的组件。这是通过对比两个新的组件树,找出共用的组件,然后检查它们的可重用性(通过&canReuse&选项)。默认情况下, 所有组件都是可重用的,除非是定制过。
2. 验证阶段
检查当前的组件是否能够停用以及新组件是否可以被激活。这是通过调用路由配置阶段的canDeactivate&和canActivate&钩子函数来判断的。
3.激活阶段
一旦所有的验证钩子函数都被调用而且没有终止切换,切换就可以认定是合法的。路由器则开始禁用当前组件并启用新组件。
此阶段对应钩子函数的调用顺序和验证阶段相同,其目的是在组件切换真正执行之前提供一个进行清理和准备的机会。界面的更新会等到所有受影响组件的&deactivate&和&activate&钩子函数执行之后才进行。
data&这个钩子函数会在&activate&之后被调用,或者当前组件组件可以重用时也会被调用。
本文主要介绍了以下内容:
介绍编写单页面应用的基本步骤
介绍嵌套路由
介绍具名路径
介绍路由对象
介绍钩子函数和执行顺序
介绍组件切换控制流水线
本文链接:文章作者:
阅读(...) 评论()
随笔 - 16138
评论 - 1392Vue-Router使用配置指南 – 那时那你
一、初始化项目
我这里使用之前搭建的Vue 2.0项目工程框架来初始化项目。详细可以参考
项目地址:
二、基本路由使用
1、构建路由页面组件
先建立几个页面组件,并包括一个404页面,当无法找到匹配路由时就使用这个404页面。几个页面组件代码如下:
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'home',
msg: 'Home'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'about',
msg: 'About'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'service',
msg: 'Service'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
&template&
&div class="flexColumnCenter notFoundPage"&
&h1&404&/h1&
&h1&找不到页面&/h1&
&/template&
export default {
name: 'notFoundPage',
msg: 'Hello Vue.js!'
methods: {
&s tyle scoped lang="scss"&
.notFoundPage{
background-color: #0a8
font-weight: 500;
&template&
&div class="hello"&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'hello',
msg: 'Hello Vue.js!'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
2、建立Vue-Router路由配置
在项目主目录src下建立router.js目录,专门用于Vue-Router路由配置。路由配置主要包括几部分内容:
(1)引入Vue-Router并使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
(2)导入需要在路由配置中使用的组件(页面)
import Home from './components/Home'
import About from './components/About'
import Service from './components/Service'
import Hello from './components/Hello'
import NotFoundPage from './components/NotFoundPage'
(3)定义路由配置项
const routes = [
{path: '/home', name: 'home', component: Home},
{path: '/about', name: 'about', component: About},
{path: '/service', name: 'service', component: Service},
{path: '/hello', name: 'hello', component: Hello},
{path: '*', component: NotFoundPage}
(4)配置并导出路由
最后一步是配置路由并将路由配置导出。Vue-Router接受一个路由选项配置和路由配置项参数,路由选项配置可以全局定义一些选项,如base(应用基路径),mode(路由模式),linkActiveClass(全局的路由激活状态样式),scrollBehavior(滚动行为)等等。路由配置项就是上面定义的各页面路由。
export default new VueRouter({
// mode: 'history',
base: '/',
scrollBehavior: function (to, from, savedPosition) {
return savedPosition
最后代码如下:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Home from './components/Home'
import About from './components/About'
import Service from './components/Service'
import Hello from './components/Hello'
import NotFoundPage from './components/NotFoundPage'
const routes = [
{path: '/home', name: 'home', component: Home},
{path: '/about', name: 'about', component: About},
{path: '/service', name: 'service', component: Service},
{path: '/hello', name: 'hello', component: Hello},
{path: '*', component: NotFoundPage}
export default new VueRouter({
// mode: 'history',
base: '/',
scrollBehavior: function (to, from, savedPosition) {
return savedPosition
3、在逻辑入口文件使用Vue-Router
在src/main.js中导入并加入路由配置。
import Vue from 'vue'
import App from './App'
import router from './router'
/* eslint-disable no-new */
render: h =& h(App)
}).$mount('#app')
在上面的配置中,将router和APP根组件一起挂载到入口文件index.html的&div id=”app”&标签
4、构建路由菜单组件
创建一个路由菜单组件,用来导航各个页面,每个路由项与路由配置一致。对于激活状态的路由,如果没有做特别配置,默认使用.router-link-active样式,所以,在这里可以定义.router-link-active的显示样式。
&template&
&div class="menu"&
&ul class="flexRowBetween"&
&li v-for="menu in menus" class="flexItem"&
&router-link :to="menu.path" tag="a" exact&{{menu.title}}&/router-link&
&/template&
export default {
name: 'vueMenu',
msg: 'Menu',
{id: 1, path: '/home', name: 'home', title: '首页'},
{id: 2, path: '/about', name: 'about', title: '关于'},
{id: 3, path: '/service', name: 'service', title: '服务'},
{id: 4, path: '/hello', name: 'hello', title: '测试'}
methods: {
&s tyle scoped lang="scss"&
@import '../css/vars.scss';
width: 100%;
background-color: $lightC
border-top: 1px solid $borderC
width: 100%;
text-align:
line-height: 4
li:not(:last-child){
border-right: 1px solid $borderC
.router-link-active{
background-color: $mainC
color: $lightC
font-size: 1.5
5、定义路由视图并使用路由
在根组件中导入上面创建的路由菜单组件,并使用&router-view&标签定义路由页面显示的区域。
&template&
&div id="app" class="flexColumnBetween"&
&router-view class="mainContainer"&&/router-view&
&vue-menu&&/vue-menu&
&/template&
import VueMenu from './components/VueMenu'
export default {
name: 'app',
components: {
width: 100
height: 100
.mainContainer{
width: 100%;
height: 100%;
overflow-y:
至此,一个基本的路由配置就完成了。运行效果如下:
三、动态路由
动态路由最典型的应用就是详情页(如新闻详情页,商品详情页等),动态路由一般是通过从主页面传递参数(如ID)到详情页面,展示详情信息。如本例使用Service页面来演示。
1、创建详情页路由配置
const routes = [
{path: '/home', name: 'home', component: Home, alias: '/'},
{path: '/about', name: 'about', component: About},
{path: '/service', name: 'service', component: Service},
{path: '/service/:id', name: 'servicedetail', component: ServiceDetail},
{path: '/hello', name: 'hello', component: Hello},
{path: '*', component: NotFoundPage}
2、建立列表页面及链接
这部分主要是对各个列表项目的链接进行配置。
&template&
&div class="flexColumnBetween page servicePage"&
&h1&{{ msg }}&/h1&
&div class="mainContent"&
&li v-for="service in services" class="flexItem"&
&router-link :to="{ path: '/service/' + service.id }"&{{service.title}}&/router-link&
&/template&
export default {
name: 'service',
msg: 'Service',
services: [
{id: 1, title: 'service1', content: 'service1 contents'},
{id: 2, title: 'service2', content: 'service2 contents'},
{id: 3, title: 'service3', content: 'service3 contents'},
{id: 4, title: 'service4', content: 'service4 contents'},
{id: 5, title: 'service5', content: 'service5 contents'}
methods: {
&s tyle scoped lang="scss"&
.servicePage{
.mainContent{
line-height: 3
padding: 0 1
border-bottom: 1px solid #
background-color: #
3、创建详情页组件
&template&
&div class="flexColumnBetween page servicePage"&
&h1&{{ msg }}&/h1&
&div class="mainContent"&
&p&{{ msg }}&/p&
&p&ID: {{serviceId}}&/p&
&p class="back" v-on:click="goback"&返回&/p&
&p class="back" v-on:click="back"&返回&/p&
&/template&
export default {
name: 'ServiceDetail',
msg: 'Service详情页面',
serviceId: null
methods: {
goback () {
this.$router.go(-1)
this.$router.back()
mounted () {
console.log(this.$route)
console.log(this.$router)
this.serviceId = this.$route.params.id
&s tyle scoped lang="scss"&
.servicePage{
.mainContent{
padding: 1
line-height: 3
text-align:
font-size: 1.5
color: #dd3333;
text-decoration:
这里需要注意以下两点:
(1)在每个路由页面,我们都可以获得$route和$router实例,使用这两个实例,可以非常方便的控制路由。
(2)上面的代码使用了$router实例的go方法和back方法来实现跳转。
(3)上面的例子从列表页点击某个列表项进行相应的列表项详情页,但有时候我们需要在列表项详情页点击进入另一个列表项详情页,如上例,从”/service/1″进入”/service/2″的时候,因为这两个页面其实是同一个,Vue-Router是不会重新渲染的,因此,当有这种需求的时候,需要动态监视页面路由的变化,这就需要用到$route实例。
现在改一下详情页ServiceDetail,使得在指定ID的详情页下也可以进入其他详情页,同时,使用watch来动态监视$route对象路由的变化,以使页面内容变化。
改过的代码如下:
&template&
&div class="flexColumnBetween page servicePage"&
&h1&{{ msg }}&/h1&
&div class="mainContent"&
&p&{{ msg }}&/p&
&p&ID: {{serviceId}}&/p&
&p class="back" v-on:click="goback"&返回&/p&
&p class="back" v-on:click="back"&返回&/p&
&li v-for="service in services" class="flexItem"&
&router-link :to="{ path: '/service/' + service.id }"&{{service.title}}&/router-link&
&/template&
export default {
name: 'ServiceDetail',
msg: 'Service详情页面',
serviceId: null,
services: [
{id: 1, title: 'service1', content: 'service1 contents'},
{id: 2, title: 'service2', content: 'service2 contents'},
{id: 3, title: 'service3', content: 'service3 contents'},
{id: 4, title: 'service4', content: 'service4 contents'},
{id: 5, title: 'service5', content: 'service5 contents'}
'$route' (to, from) {
console.log(to)
console.log(from)
this.serviceId = to.params.id
methods: {
goback () {
this.$router.go(-1)
this.$router.back()
mounted () {
console.log(this.$route)
console.log(this.$router)
this.serviceId = this.$route.params.id
&s tyle scoped lang="scss"&
.servicePage{
.mainContent{
padding: 1
line-height: 3
text-align:
font-size: 1.5
color: #dd3333;
text-decoration:
line-height: 3
padding: 0 1
border-bottom: 1px solid #
background-color: #
运行效果:
四、嵌套路由
Vue-Router可以在一个路由页面视图下再嵌套视图,最典型的就是我们常见的Tabs标签式导航。下面一个小例子演示嵌套路由制作一个简单的Tab标签导航。
1、首先制作三个Tab子页面组件
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'AboutOne',
msg: 'About页面的第一个页面'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'AboutTwo',
msg: 'About页面的第二个页面'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
&template&
&h1&{{ msg }}&/h1&
&/template&
export default {
name: 'AboutThree',
msg: 'About页面的第三个页面'
methods: {
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
2、配置嵌套路由
改写原来的About路由项,使用children配置项配置嵌套路由
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Home from './components/Home'
import About from './components/About'
import AboutOne from './components/AboutOne'
import AboutTwo from './components/AboutTwo'
import AboutThree from './components/AboutThree'
import Service from './components/Service'
import ServiceDetail from './components/ServiceDetail'
import Hello from './components/Hello'
import NotFoundPage from './components/NotFoundPage'
const routes = [
{path: '/home', name: 'home', component: Home, alias: '/'},
path: '/about',
name: 'about',
component: About,
children: [
{path: '/about/aboutone', component: AboutOne},
{path: '/about/abouttwo', component: AboutTwo},
{path: '/about/aboutthree', component: AboutThree}
{path: '/service', name: 'service', component: Service},
{path: '/service/:id', name: 'servicedetail', component: ServiceDetail},
{path: '/hello', name: 'hello', component: Hello},
{path: '*', component: NotFoundPage}
export default new VueRouter({
// mode: 'history',
base: '/',
scrollBehavior: function (to, from, savedPosition) {
return savedPosition
3、加入Tab路由菜单项,使用嵌套路由
&template&
&div class="flexColumnBetween page aboutPage"&
&h1&{{ msg }}&/h1&
&ul class="flexRowBetween"&
&li v-for="menu in menus" class="flexItem center"&
&router-link :to="menu.path" tag="a"&{{menu.title}}&/router-link&
&div class="mainContent"&
&router-view&&/router-view&
&/template&
export default {
name: 'about',
msg: 'About',
{id: 1, path: '/about/aboutone', name: 'aboutone', title: 'AboutOne'},
{id: 2, path: '/about/abouttwo', name: 'abouttwo', title: 'AboutTwo'},
{id: 3, path: '/about/aboutthree', name: 'aboutthree', title: 'AboutThree'}
currentPage: null
&s tyle scoped lang="scss"&
.aboutPage{
a{border-bottom: 2px solid #}
.router-link-active{
border-bottom: 2px solid #dd3333;
li:not(:last-child){
border-right: 1px solid #
.active{color: #dd3333;}
以上配置后,一个简单的tab标签式导航效果就可实现了。不过这里存在一个问题,就是当使用/about路径时,我们会看到没有与之匹配的组件页面显示,这种Tabs标签很多时候会默认显示一个tab子页面,最简单的我们可以通过alias来做,假如默认显示第一个tab子页面,只需要在路由配置中第一个tab页面配置加入alias,指向’/about’即可。如下:
path: '/about',
name: 'about',
component: About,
children: [
{path: '/about/aboutone', component: AboutOne, alias: '/about'},
{path: '/about/abouttwo', component: AboutTwo},
{path: '/about/aboutthree', component: AboutThree}
默认的tab视图已显示出来了,这时候一个新的问题是,当前激活视图的菜单样式在/about这个父级页面路径时不起效果。这时候可以手动处理一下,通过动态获取当前的路由路径,如果当前路由路径是父级页面路径/about时,则加上路由激活样式。此时About页面组件代码如下:
&template&
&div class="flexColumnBetween page aboutPage"&
&h1&{{ msg }}&/h1&
&ul class="flexRowBetween"&
&li v-for="menu in menus" class="flexItem center"&
&router-link :to="menu.path" tag="a" exact v-bind:class="{ 'router-link-active': currentPage == '/about' && menu.path == '/about/aboutone'}"&{{menu.title}}&/router-link&
&div class="mainContent"&
&router-view&&/router-view&
&/template&
export default {
name: 'about',
msg: 'About',
{id: 1, path: '/about/aboutone', name: 'aboutone', title: 'AboutOne'},
{id: 2, path: '/about/abouttwo', name: 'abouttwo', title: 'AboutTwo'},
{id: 3, path: '/about/aboutthree', name: 'aboutthree', title: 'AboutThree'}
currentPage: null
'$route' (to, from) {
this.currentPage = to.path
mounted () {
this.currentPage = this.$route.path
&s tyle scoped lang="scss"&
.aboutPage{
a{border-bottom: 2px solid #}
.router-link-active{
border-bottom: 2px solid #dd3333;
li:not(:last-child){
border-right: 1px solid #
.active{color: #dd3333;}
运行效果:
五、编程式导航
Vue-Router除了可以使用&router-link&来实现导航链接,还可以通过$router实例内置方法来实现链接跳转。主要的方法有push/replace/go三个,这三个方法都可以实现跳转,不同的是push是在当前的路由栈中加入新的路由,replace是直接替换掉当前的路由,go则是依据目前的路由栈,通过传入一个整型参数,来实现向前或向后跳转的路由数。
这里简单通过前面示例中的Home页面来演示:
&template&
&h1&{{ msg }}&/h1&
&a v-on:click="goto(1)"&跳转至关于页面&/a&
&a v-on:click="goto(2)"&跳转至关于页面的第二个标签页面&/a&
&a v-on:click="goto(3)"&跳转至服务页面的第3条服务信息&/a&
&a v-on:click="goto(4)"&跳转至测试页面&/a&
&/template&
export default {
name: 'home',
msg: 'Home'
methods: {
goto (param) {
console.log(this.$router)
console.log(this.$route)
switch (param) {
this.$router.push('about')
this.$router.push('/about/abouttwo')
this.$router.push({name: 'servicedetail', params: {id: 3}})
this.$router.push({name: 'hello'})
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
padding: 10
font-size: 16
color: #dd3333;
padding: 10px 0;
六、过渡动画
Vue-Router还可以通过Vue的transition组件实现路由页面间的过渡。transition页面过渡效果主要依赖于CSS3来实现。在Vue-Router中实现路由过渡动效非常简单,只需要定义transition组件,并指定过渡动效名即可。
下面通过简单例子演示Vue-Router中的过渡动效:
1、定义过渡动效:
.slide-fade-enter-active {
transition: all .5
.slide-fade-leave-active {
transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
.slide-fade-enter, .slide-fade-leave-to{
transform: translateX(10px);
opacity: 0;
2、在路由页面组件中加入动效组件
&template&
&transition name="slide-fade"&
&h1&{{ msg }}&/h1&
&/transition&
&/template&
更多关于Vue的Transiton效果详情,请参考
七、Vue-Router导航钩子
Vue-Router提供了三个级别的路由钩子,即全局钩子、特定路由独享的钩子和组件内的钩子。通过“导航钩子”, 可以非常方便对整个路由响应过程进行控制。
1、全局钩子影响全局,所有路由跳转都会触发
使用router.beforeEach 注册全局的before钩子:
import Vue from 'vue'
import App from './App'
import router from './router'
console.log(router)
router.beforeEach((to, from, next) =& {
console.log('这是一个全局钩子')
console.log(to)
console.log(from)
console.log(next)
next(true)
/* eslint-disable no-new */
render: h =& h(App)
}).$mount('#app')
2、特定路由独享钩子只影响该特定路由
特定路由独享钩子在路由配置上直接定义,如下面的 beforeEnter 钩子:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Home from './components/Home'
import About from './components/About'
import AboutOne from './components/AboutOne'
import AboutTwo from './components/AboutTwo'
import AboutThree from './components/AboutThree'
import Service from './components/Service'
import ServiceDetail from './components/ServiceDetail'
import Hello from './components/Hello'
import NotFoundPage from './components/NotFoundPage'
const routes = [
{path: '/home', name: 'home', component: Home, alias: '/'},
path: '/about',
name: 'about',
component: About,
beforeEnter: (to, from, next) =& {
console.log('这是一个路由钩子,进入了about')
console.log(to)
console.log(from)
console.log(next)
next(true)
children: [
{path: '/about/aboutone', component: AboutOne, alias: '/about'},
{path: '/about/abouttwo', component: AboutTwo},
{path: '/about/aboutthree', component: AboutThree}
{path: '/service', name: 'service', component: Service},
{path: '/service/:id', name: 'servicedetail', component: ServiceDetail},
{path: '/hello', name: 'hello', component: Hello},
{path: '*', component: NotFoundPage}
export default new VueRouter({
// mode: 'history',
base: '/',
scrollBehavior: function (to, from, savedPosition) {
return savedPosition
3、组件内钩子定义于组件内部
组件内钩子直接在组件内定义,有beforeRouteEnter、beforeRouteUpdate和beforeRouteLeave三种组件内钩子。
&template&
&transition name="slide-fade"&
&h1&{{ msg }}&/h1&
&/transition&
&/template&
export default {
name: 'AboutOne',
msg: 'About页面的第一个页面'
methods: {
beforeRouteEnter (to, from, next) {
console.log('这是一个组件内钩子:beforeRouteEnter,进入了about页面第一个子页面')
console.log(to)
console.log(from)
console.log(next)
next(true)
beforeRouteUpdate (to, from, next) {
console.log('这是一个组件内钩子:beforeRouteUpdate,进入了about页面第一个子页面更新了')
console.log(to)
console.log(from)
console.log(next)
next(true)
beforeRouteLeave (to, from, next) {
console.log('这是一个组件内钩子:beforeRouteLeave,离开了about页面第一个子页面')
console.log(to)
console.log(from)
console.log(next)
let sureClose = confirm('确定关闭吗?')
next(sureClose)
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
(1)在完成路由操作时,要调用next方法,以使路由钩子继续执行下去,完成路由导航;
(2)组件内路由钩子的beforeRouteEnter是在渲染组件前就已经调用,因此在这个方法下,$this无法使用。
八、数据获取
使用过AngularJS的ui-router的都知道,我们可以根据实际项目需要,在路由页面(导航)“进入前”或“进入后”去获取远程数据。
1、在路由页面进入后请求数据
&template&
&transition name="slide-fade"&
&h1&{{ msg }}&/h1&
&p v-if="!posts.length"&正在加载数据...&/p&
&div v-if="posts.length"&{{posts}}&/div&
&/transition&
&/template&
import axios from 'axios'
export default {
name: 'AboutTwo',
msg: 'About页面的第二个页面',
mounted () {
this.fetchData()
methods: {
fetchData () {
let that = this
axios.get('http://localhost:3000/posts')
.then(function (response) {
console.log(response)
that.posts = response.data.data
.catch(function (error) {
console.log(error)
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
2、在路由页面进入前请求数据
&template&
&transition name="slide-fade"&
&h1&{{ msg }}&/h1&
&div v-if="posts.length"&{{posts}}&/div&
&/transition&
&/template&
import axios from 'axios'
export default {
name: 'AboutThree',
msg: 'About页面的第三个页面',
methods: {
beforeRouteEnter (to, from, next) {
axios.get('http://localhost:3000/posts')
.then(function (response) {
console.log(response)
if (response.status === 200 && response.data.status) {
next(vm =& {
vm.posts = response.data.data
next(false)
.catch(function (error) {
console.log(error)
next(false)
&s tyle scoped lang="scss"&
$color: #dd3333;
text-align:
font-weight:
以上就是关于Vue-Router的主要介绍内容,更多细节详情可参考。
本文示例代码已托管至
随遇,随缘,随安,随喜!
除特别说明外,本站所有文章均为原创,转载请注明出处和链接。感谢您对本站的支持,感谢您对知识的尊重!

我要回帖

更多关于 vue routerlinkactive 的文章

 

随机推荐