安装
script
<script src="./vue-router.js"></script>
cdn
不指定使用版本
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
指定使用版本
<script src="https://unpkg.com/vue-router@3.3.4/dist/vue-router.js"></script>
npm
npm install -S vue-router
配置
注: 在cli中的配置
基本配置
main.js
// 1.注册VueRouter插件
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
// 2.定义路由
import Index from '@/views/index/Index.vue';
import User from '@/views/user/User.vue';
const routes = [{
path: '/index',
component: Index
}, {
path: '/user',
component: User
}];
// 3.实例化router
const router = new VueRouter({
routes
});
// 4.注册路由
// 将router对象挂载到vue全局属性上,
// 则在任意组件可以使用this.$router访问到router实例
// 通过this.$route访问当前路由
new Vue({
router,
render: h => h(App)
}).$mount('#app');
嵌套路由
使用children字段配置;
children配置字段与外层routes配置字段相同;
const routes = [{
path: '/user',
component: User,
children: [{
// 访问路径: '/user/base-info'
path: 'base-info',
component: UserBaseInfo
}, {
// 访问路径: '/link-us'
path: '/link-us',
component: UserLinkUs
}]
}];
组件配置:
User.vue
<template>
<!-- 子路由渲染位置 -->
<router-view></router-view>
</template>
命名路由
使用name字段配置
const routes = [{
path: '/user',
name: 'user',
component: User
}]
路由元信息
使用meta字段配置
const routes = [{
path: '/user',
meta: {
requiresAuth: true
},
component: User
}];
获取meta信息
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
动态路由
const routes = [{
// 匹配路径 /user/123
path: '/user/:userid'
component: User
}];
获取动态路由参数 User.vue
<template>
<div>
userid: {{ $route.params.userid }}
</div>
</template>
<script>
export default {
computed: {
userid() {
return this.$route.params.userid;
}
},
created() {
console.log(this.$route.params.userid);
}
}
</script>
重定向与别名
重定向 - redirect
- 值为字符串路径
const routes = [{
path: '*',
redirect: '/index'
}];
- 值为路由名称
const routes = [{
path: '*',
redirect: {
name: 'user'
}
}];
- 是一个方法,返回重定向目标
const routes = [{
path: '*',
redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}
}]
别名 - alias
const routes = [{
path: '/index',
alias: '/home'
}];