一、路由配置
第一步: 引入vue-router构造函数
第二步: 引入路由组件
第三步: 定义路由规则
第四步: 创建路由对象,并将路由规则传递给路由对象
第五步: 将路由实例对象挂载vue根实例上
// 第一步:引入vue-router构造函数
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 第二步:引入路由组件
import Index from './views/Index'
import Category from './views/Category'
import Cart from './views/Cart'
import User from './views/User'
import NotFound from './views/NotFound'
// 第三步: 定义路由规则
const routes = [
// path:'/' 表示根路径
{ path: '/', redirect: { name: 'index' } }, // 路由重定向
{ path: '/index', component: Index, name: "index" },
{ path: '/category', component: Category, name: "category" },
{ path: '/cart', component: Cart, name: "cart" },
{ path: '/user', component: User, name: "user" },
// 配置404路由
{ path: "*", component: NotFound }
]
// 第四步: 创建路由对象,并将路由规则传递给路由对象
const router = new VueRouter({
mode: 'history',
routes
})
new Vue({
el: '#app',
router, //第五步: 将路由实例对象挂载vue根实例上
render: (h) => h(App),
})
二、路由导航方式
1、声明式导航
<router-link to="/xxxxx">首页</router-link>
2、编程式导航及传参
// 跳转传参
this.$router.push({ path: path, query: { 参数 } })
// 接收
this.$route.query
三、路由嵌套
比如有一个/users
的路由,那么/users
下面还可以添加子级路由,如:/users/index
、/users/add
等等,这样的路由情形称之为嵌套路由
// 在路由配置中
{
path: '/user', // 一级路由
component: User,
name: "user",
children: [ //二级路由
{
path: '/user/infoone',
component: InfoOne,
name: "infoone",
children: [
]
},
{
path: 'infotwo',
component: InfoTwo,
name: "infotwo"
}
]
}
四、路由守卫
1、全局前置守卫:路由跳转前执行一些操作router.beforeEach
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// to 即将进入的路由
// from 上一个路由信息对象
// next 放行函数
})
2、路由独享守卫:某个路由路径独享的守卫 beforeEnter
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// 与全局前置守卫参数一样
// ...
}
}
]
})
3、组件内地守卫:组件内定义,类似于路由独享守卫
<template>
<div>某页面</div>
</template>
<script>
export default {
data() {
return {};
},
beforeRouteEnter(to, from, next) {
// 路由进入当前组件前
next();
},
beforeRouteUpdate(to, from, next) {
// 路由更新前
next();
},
beforeRouteLeave(to, from, next) {
// 路由离开前
// 可以跳转到下一个页面的时候,做一些逻辑操作
next();
},
};
</script>