安装

  1. 直接下载(官方CDN)

https://unpkg.com/vue-router/...
通过页面script标签引入,如下:

<script src='https://unpkg.com/vue-router/dist/vue-router.js'></script>
  1. NPM安装
npm install vue-router --save-dev

安装完成后需要Vue.use()安装此功能,例如:

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

入门

  1. 简单例子

<html>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>vue1217</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

<App.vue>

<template>
<div>
<p>
<router-link to="/foo">Foo Link</router-link>
<router-link to="/bar">Bar Link</router-link>
</p>
<router-view></router-view>
</div>
</template> <script type="text/ecmascript-6">
export default {};
</script> <style lang="stylus" rel="stylesheet/stylus"> </style>

<main.js>

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App'; Vue.use(VueRouter); const foo = {
template: '<div>foo</div>'
};
const bar = {
template: '<div>bar</div>'
}; const routes = [{
path: '/foo',
component: foo
}, {
path: '/bar',
component: bar
}]; let router = new VueRouter({
routes
}); /* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
});
  1. 动态路由匹配

通过带有冒号标记的属性匹配,例如

path: '/foo/test0'
path: '/foo/test1'
都可以被
path: '/foo/:id'
匹配到
并且被匹配到的组件内部可以通过
this.$route.params获取到被匹配的参数
如上:
test0组件下的params参数为
{
id: 'test0'
} 同样的:
/foo/test0/jason/0411

/foo/:id/:name/:birth
匹配到的参数如
{
id: 'test0',
name: 'jason',
birth: '0411'
}

小提示:对于通过路由进行组件间的切换时,并不会来回构建组件实例,而是复用已存在的组件,想要监听路由参数变化可以通过watch属性或者通过beforeRouteUpdate钩子函数做操作

{
watch: {
'$route'(to, from) {
// something to do
}
}
}
{
beforeRouteUpdate(to, from, next) {
// something to do
next();// next必须执行不然的话beforeRouteUpdate钩子函数不会resolved
}
}
  1. 嵌套路由

顾名思义就是路由跳到的组件又包含有路由。
举个栗子:

<App.vue>
<template>
<div>
<p>
<router-link to="/foo">foo</router-link>
<router-link to="/foo1/hm">foo1</router-link>
<router-link to="/foo2/pf">foo2</router-link>
<router-link to="/foo3/ps">foo3</router-link>
</p>
<router-view></router-view>
</div>
</template> const foo = {
template: `
<div>
<p>{{ $route.params.id }}</p>
<router-view></router-view>
</div>
`
};
<main.js>
const home = {
template: '<div>home</div>'
};
const hm = {
template: '<div>hm</div>'
};
const pf = {
template: '<div>pf</div>'
};
const ps = {
template: '<div>ps</div>'
}; const routes = [{
path: '/:id',
component: foo,
children: [
{
path: '',
component: home
}, {
path: 'hm',
component: hm
}, {
path: 'pf',
component: pf
}, {
path: 'ps',
component: ps
}
]
}];
  1. 通过$router导航

在组件Vue实例内部可以通过
this.$router.push(location, onComplete?, onAbort?)
this.$router.replace(location, onComplete?, onAbort?)
this.$router.go(n)

// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }}) const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user // 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
  1. 命名路由

在创建路由的时候可以通过name属性设置路由名称

let routes = [{
path: '/foo/:userId',
name: 'test',
component: User
}];

如果需要链接到这个命名路由我们可以酱紫

<router-link :to="{ 'name' : 'test', 'params' : { 'userId' : 410100 }}"></router-link>

也可以酱紫

router.push({
name: 'test',
params: {
userId: 410100
}
});
  1. 命名视图

很多时候我们会碰到并存的多个视图(router-view),我们就需要为视图设置name没有设置的为default

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

当然构建路由的时候也需要设置对应视图的组件映射

const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
  1. 重定向
let routes = [{
path: '/',
redirect: '/goods'
},{
path: '/goods',
component: goods
}];
当path为/的时候会自动重定向至/goods加载goods组件
当然也可以通过name重定向,作用是相同的
let routes = [{
path: '/',
redirect: {
name: 'goods'
}
},{
path: '/goods',
name: 'goods',
component: goods
}];
当然也可以是一个方法
let routes = [{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}];
  1. 别名

别名与重定向只有一丢丢不同,重定向指/a路径调到/b路径加载,别名指还是加载/a路径只是加载内容是/b路径下的

const router = new VueRouter({
routes: [{
path: '/a',
component: A,
alias: '/b'
}]
});

5.路由参数传递
有三种模式进行传递:布尔模式、对象模式、函数模式
布尔模式: 如果props被设置为true,route.params将会被设置为组件属性。

router-link的路径
<router-link to="/foo/params">foo</router-link> foo的路由
{
path: '/foo/:userName',
name: 'foo',
component: foo,
props: true
} foo组件
<template>
<div>
foo
<div>{{userName}}</div>
</div>
</template> <script type="text/ecmascript-6">
export default {
props: {
userName: {
type: String,
default: ''
}
}
};
</script>

点击router-link后的结果

你会发现/foo/params被path匹配后

route.params =  {
userName: 'params'
};

props中的userName就会接收到字符串'params',因此输出结果如图所示

对象模式:如果props是一个对象,它会被按原样设置为组件属性。

{
path: '/foo',
name: 'foo',
component: foo,
props: {
userName: 'From Obj'
}
}

渲染后的结果:

函数模式

{
path: '/foo',
name: 'foo',
component: foo,
props: (route) => ({userName: route.query.name})
}

看起来还是很清楚的,只是props会接收一个当前的路由参数,将参数中的值转换成你想要的值,以上三种模式自然也不影响通过router-view的v-bind:user-name这种方式传递,但是对于同名的参数值会有影响。

let lastProps = {};
let vBindProps = {
userName: 'vBind',
name: 'vBind'
};
let routeProps ={
userName: 'route'
};
Object.assign(lastProps,vBindProps,routeProps);
// {userName: "route", name: "vBind"}
最终的lastProps就是传入的props

最新文章

  1. 使用System Sound Services 播放音效(最简单,比较底层),调用AudioServicesPlaySystemSound()
  2. PE文件结构部分解析以及输入的定位
  3. HDU 4282 A very hard mathematic problem 二分
  4. VC 串口通信类
  5. Oauth2认证以及新浪微博开放平台应用
  6. HDU 5755 Gambler Bo
  7. bootstrap html页面禁止放大缩小
  8. Openstack中RabbitMQ RPC代码分析
  9. 解决OrangePi 耳机孔没有声音
  10. 关于vs调用数据库存储过程 返回输出参数的一些总结
  11. 积累的关于linux的安装卸载软件基本命令
  12. URAL 1501 Sense of Beauty
  13. (CoreText框架)NSAttributedString 2
  14. PHP error_log 实际运用
  15. BZOJ2301:[HAOI2011]Problem b——题解
  16. java运行顺序-JVM之九
  17. struct&amp;&amp;class 空的大小
  18. Travelling (三进制+状压dp)
  19. 利用Python进行数据分析 2017 第二版 项目代码
  20. WPF 模拟Button按钮事件触发

热门文章

  1. linux 文件描述符表 打开文件表 inode vnode
  2. simple config of webpack
  3. `GLIBCXX_3.4.15&#39; not found when using mex file in matlab (linux)
  4. 012 Android 动画效果(补间动画) +去掉App默认自带的标题+更改应用的图标
  5. nginx location 路由的几个配置纪要
  6. 在CentOS下搭建GoLang开发环境
  7. Python26之字典2(内置函数)
  8. python 并发的开端
  9. Appscan 的安装与使用
  10. 列主元消去法&全主元消去法——Java实现