Vue Router高级
路由组件传参
通过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参数将被设置为组件属性
对象模式
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
]
})
函数模式
/search?q=vue 会将{query:vue}传递给组件SearchUser
const router = new VueRouter({
routes: [
{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
]
})
History模式
vue-router默认使用hash模式
const router = new VueRouter({
mode: 'history',
routes: [...]
})
如果使用history模式,URL就像正常url,http://mysite.com/user/id
这种模式需要后台配置
警告:所有路径都会返回index.html,因此需要配置一个404页面
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
导航守卫
全局前置守卫
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
三个参数
to:即将进入的Route
from:当前导航离开的Route
next:
next()进行管道中的下一个钩子
next(false)中断当前导航
next('/')或next({path:'/'}) 中断当前导航,跳转到下一个导航
一个登陆案例,根据用户是否登录判断路由跳转
router.beforeEach((to, from, next) => {
// 如果不是登录页
if (to.name !== 'login') {
if (HAS_LOGIN) next()
else next({ name: 'login' })
} else {
if (HAS_LOGIN) next({ name: 'home' })
else next()
}
})
全局后置钩子
router.afterEach((to, from) => {
// ...
})
一个页面加载的案例。loading设置
路由独享守卫
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
组件内的守卫
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
}
完整的导航流出
https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#组件内的守卫
路由元信息
定义路由可以配置meta字段
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})
我们在全局导航守卫中调用
case
router.beforeEach((to, from, next) => {
console.log(to)
})
fullPath: "/foo/bar"
hash: ""
matched: () [{…}, {…}]
meta: {requireAuth: true}
name: "bar"
params: {}
path: "/foo/bar"
query: {}
__proto__: Object
我们能从to中获得meta中数据
router.beforeEach((to, from, next) => {
const requireAuth = to.meta.requireAuth
if (requireAuth) {
if (HAS_LOGIN) next()
else next({ 'name': 'login' })
} else {
next()
}
})
过渡效果
<transition>
<router-view></router-view>
</transition>
单个路由过渡
const Foo = {
template: `
<transition name="slide">
<div class="foo">...</div>
</transition>
`
}
const Bar = {
template: `
<transition name="fade">
<div class="bar">...</div>
</transition>
`
}
数据获取
导航完成后获取数据
$router.params.id获得文章数据
<template>
<div class="post">
<div class="loading" v-if="loading">
Loading...
</div> <div v-if="error" class="error">
{{ error }}
</div> <div v-if="post" class="content">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
export default {
data () {
return {
loading: false,
post: null,
error: null
}
},
created () {
// 组件创建完后获取数据,
// 此时 data 已经被 observed 了
this.fetchData()
},
watch: {
// 如果路由有变化,会再次执行该方法
'$route': 'fetchData'
},
methods: {
fetchData () {
this.error = this.post = null
this.loading = true
// replace getPost with your data fetching util / API wrapper
getPost(this.$route.params.id, (err, post) => {
this.loading = false
if (err) {
this.error = err.toString()
} else {
this.post = post
}
})
}
}
}
在导航完成前获得数据beforeRouterEnter
export default {
data () {
return {
post: null,
error: null
}
},
beforeRouteEnter (to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
// 路由改变前,组件就已经渲染完了
// 逻辑稍稍不同
beforeRouteUpdate (to, from, next) {
this.post = null
getPost(to.params.id, (err, post) => {
this.setData(err, post)
next()
})
},
methods: {
setData (err, post) {
if (err) {
this.error = err.toString()
} else {
this.post = post
}
}
}
}
滚动行为
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滚动到哪个的位置
}
})
当切换到新的路由时候,想要页面滚动到顶部,或者原先的位置
scrollBehavior (to, from, savedPosition) {
return { x: , y: }
}
路由懒加载
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})
Vue Router高级的更多相关文章
- vue Router——基础篇
vue--Router简介 vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用. vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路 ...
- Vue.js路由管理器 Vue Router
起步 HTML <script src="https://unpkg.com/vue/dist/vue.js"></script> <script s ...
- vue路由高级用法
五.路由设置高级用法alias 别名 {path:'/list',component:MyList,alias:'/lists'}redirect 重定向 {path:'/productList',r ...
- Vue 2.0 + Vue Router + Vuex
用 Vue.js 2.x 与相配套的 Vue Router.Vuex 搭建了一个最基本的后台管理系统的骨架. 当然先要安装 node.js(包括了 npm).vue-cli 项目结构如图所示: ass ...
- vue router 只需要这么几步
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- Vue.js 2.x笔记:路由Vue Router(6)
1. Vue Router简介与安装 1.1 Vue Router简介 Vue Router 是 Vue.js 官方的路由管理器.它和 Vue.js 的核心深度集成,构建单页面应用. Vue Rout ...
- Vue Router学习笔记
前端的路由:一个地址对应一个组件 Vue Router中文文档 一.路由基本使用 第1步:导入Vue Router: <script src="https://unpkg.com/vu ...
- vue router.push(),router.replace(),router.go()和router.replace后需要返回两次的问题
转载:https://www.cnblogs.com/lwwen/p/7245083.html https://blog.csdn.net/qq_15385627/article/details/83 ...
- 前端MVC Vue2学习总结(八)——Vue Router路由、Vuex状态管理、Element-UI
一.Vue Router路由 二.Vuex状态管理 三.Element-UI Element-UI是饿了么前端团队推出的一款基于Vue.js 2.0 的桌面端UI框架,手机端有对应框架是 Mint U ...
随机推荐
- termcap - 终端功能数据库
描述 DESCRIPTION termcap 数据库是一个过时 (obsolete) 工具,用来描述以字符为单位的终端和打印机的功能.它之所以被保留,是为了兼容古老的程序:新程序应当使用 termin ...
- JS window对象 Location对象 location用于获取或设置窗体的URL,并且可以用于解析URL。 语法: location.[属性|方法]
Location对象 location用于获取或设置窗体的URL,并且可以用于解析URL. 语法: location.[属性|方法] location对象属性图示: location 对象属性: lo ...
- JQuery 浮动DIV显示提示信息并自动隐藏
/** * 浮动DIV定时显示提示信息,如操作成功, 失败等 * @param string tips (提示的内容) * @param int height 显示的信息距离浏览器顶部的高度 * @p ...
- Linux 常用的一些操作
1.查看linux中某个端口是否被占用 1> 使用lsof lsof -i:端口号 查看该端口是否被占用 2> 使用netstat netstat -antpu |grep 80 ...
- bzoj1001 [ICPC-Beijing 2006]狼抓兔子
我满心以为本题正解为最短路,结果到处都是最大流…… 几乎所有的都写了什么“对偶图”跑最短路,但我真的不知道什么叫做对偶图---------------------------------------- ...
- RN 真机roload
第四步:打开调试菜单 手机设备可以通过摇一摇设备打开调试菜单,也可以打开调试菜单. 可因为是平板,摇一摇不是太方便,可以在电脑端运行命令来打开调试菜单,但有时却又无法打开调试菜单(如果是使用真机调试, ...
- Linux环境进程间通信----系统 V 消息队列(二)
一.消息队列是一条由消息连接而成的链表,它保存在内核中,通过消息队列的引用标示符来访问. 二.消息队列不同于管道,通信的两个进程可以是完全无关的进程,它们之间不需要约定同步的方法.只要消息队列存在并且 ...
- Golang 标准库log的实现
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://gotaly.blog.51cto.com/8861157/1406905 前 ...
- Java异常关闭资源的两种方式
try-catch-finally 常用,在异常关闭时应判断流是否为空 public class CloseableUtils { public static void closeable(Close ...
- Java服务定位器模式
当我们想要使用JNDI查找来定位各种服务时,使用服务定位器设计模式. 考虑到为服务查找JNDI的高成本,所以在服务定位器模式使用缓存技术. 首次需要服务时,服务定位器在JNDI中查找并缓存服务对象. ...