记录一些Vue路由笔记

444 阅读3分钟

Vue 路由

相关 API 说明

1. VueRouter(): 用于创建路由器的构建函数 
	new VueRouter({ 
		// 多个配置项 
	}) 
2. 路由配置 
	routes: [ 
        { 
            // 一般路由 
            path: '/about', 
            component: About 
        },
        { 
            // 自动跳转路由 
            path: '/', 
            redirect: '/about' 
        } 
	] 
3. 注册路由器
	import router from './router' 
	new Vue({ 
		router 
	}) 
4. 使用路由组件标签 
    1. : 用来生成路由链接 Go to XXX 
    2. : 用来显示当前路由组件界面

应用组件:App.vue

<div>
    <!--路由链接-->
    <router-link to="/about">About</router-link>
    <router-link to="/home">Home</router-link>
    <!--用于渲染当前路由组件-->
    <router-view></router-view>
</div>

路由器模块: src/router/index.js

export default new VueRouter({
    routes: [
        {
            path: '/', 
            redirect: '/about' 
        },
        {
            path: '/about', 
            component: About
        },
        {
        	path: '/home', 
        	component: Home
        }
    ]
})

注册路由器: main.js

import Vue from 'vue' 
import router from './router' 
// 创建 vue 配置路由器
new Vue({
	el: '#app', 
	router, 
	render: h => h(app)
})

优化路由器配置

 linkActiveClass: 'active', // 指定选中的路由链接的 class

总结: 编写使用路由的 3 步

1) 定义路由组件 
2) 注册路由 
3) 使用路由
    <router-link>
    <router-view>

嵌套路由

配置嵌套路由: router.js

path: '/home', 
component: home, 
children: [ 
	{ 
		path: 'news', 
		component: News 
	},
	{ 
        path: 'message', 
        component: Message 
	} 
]

路由链接: Home.vue

<router-link to="/home/news">News</router-link>
<router-link to="/home/message">Message</router-link>
<router-view></route-view>

向路由组件传递数据

方式 1: 路由路径携带参数(param/query)

1) 配置路由
children: [
    {
    	path: 'mdetail/:id', 	//param 传参
		path: 'mdetail', 		//query 传参
    	component: MessageDetail
    }
]
2) 路由路径
<router-link :to="`/home/message/mdetail/${m.id}`">{{m.title}}</router-link>	//param 传参
<router-link :to="`/home/message/mdetail?id=${m.id}`">{{m.title}}</router-link>	//query 传参
3) 路由组件中读取请求参数
this.$route.params.id
this.$route.query.id

方式 2: 属性携带数据

<router-view :msg="msg"></router-view>

缓存路由组件对象

理解

1) 默认情况下, 被切换的路由组件对象会死亡释放, 再次回来时是重新创建的 
2) 如果可以缓存路由组件对象, 可以提高用户体验

编码实现

<keep-alive>
	<router-view></router-view>
</keep-alive>

编程式路由导航

相关 API

1) this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
2) this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
3) this.$router.back(): 请求(返回)上一个记录路由
4) this.$router.go(-1): 请求(返回)上一个记录路由
5) this.$router.go(1): 请求下一个记录路由

全局前置守卫

你可以使用 router.beforeEach 注册一个全局前置守卫:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

每个守卫方法接收三个参数:
to: Route: 即将要进入的目标 路由对象
from: Route: 当前导航正要离开的路由
next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

示例:
router.beforeEach((to, from, next) => {
  if (to.path !== '/home') {
    if (store.getters.getLoginState) {
      next();
    }
    else {
      next({ path: '/home' });
    }
  } else {
    next();
  }
})

组件内的守卫

beforeRouteEnter 示例
import store from "../store";
export default {
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    if (to.path !== "/home") {
      if (store.getters.getLoginState) {
        next();
      } else {
        next({ path: "/home" });
      }
    } else {
      next();
    }
  },
};
//如果想获取vuex中的属性,由于没有this,所以可以通过引入store对象来获取