Vue Router使用要点简介
一、Vue Router的基本使用
1、安装vue-router插件
npm install vue-router --save
链接:Vue Router文档
2、创建路由实例
import Vue from 'vue'
import VueRouter from 'vue-router'
import listTemplate from '@/view/demo/listTemplate.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/demo',
component: listTemplate
}
]
const router = new VueRouter({
routes
})
export default router
3、挂载到Vue实例上
import Vue from 'vue'
import App from './App'
import router from '@/router/index'
Vue.use(ElementUI)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
router,
template: '<App/>'
})
4、使用路由
二、Vue Router的基础进阶
1、动态路由匹配
把某种模式匹配到的所有路由,全都映射到同个组件。
const router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
})
一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在User 组件内使用。
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
注意:
用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用,但是组件的生命周期钩子不会再被调用。
若想对路由参数的变化作出响应,就要使用 watch (监测变化) $route 对象:
const User = {
template: '...',
watch: {
$route(to, from) {
// 对路由变化作出响应...
}
}
}
2、捕获所有路由或 404 Not found 路由
路由 { path: '*' }
通常用于客户端 404 错误,当使用通配符路由时,含有通配符的路由应该放在最后。
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}
注意:
路由定义得越早,优先级就越高。
3、命名路由
通过一个名称来标识一个路由
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
4、 命名视图
如果 router-view 没有设置名字,那么默认为 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>
一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components 配置 (带上 s):
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
5、重定向
从 /a 重定向到 /b
const router = new VueRouter({
routes: [
{
path: '/a',
redirect: '/b' }
]
})
6、别名
当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。
const router = new VueRouter({
routes: [
{
path: '/a',
component: A,
alias: '/b' }
]
})
7、路由组件传参
通过 props 解耦
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
说明:
如果 props 被设置为 true,route.params 将会被设置为组件属性
8、HTML5 History模式
(1)vue-router 默认 hash 模式(在url中带#号):
window可以监听到哈希值的变化(onhashchage事件),当url中的哈希值发生了变化,无需再向服务器发起http请求,window可以监听到这种变化,并按需加载前端的代码块。路由分发不需要服务器来做,前端自己就可以完成。于是当 URL 改变时,页面不会重新加载。
(2)路由的 history 模式(在url中不带#号):
用的是传统的路由分发模式,即当用户输入一个url时,由服务器接受用户的输入请求,并解析url的路径然后做相应逻辑处理。
const router = new VueRouter({
mode: 'history',
routes: [...]
})