阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
利用JS实现路由跳转
代码示例:/lesson10/01. vue-router 最基本的路由.html
使用this.$router.push方法可以实现路由跳转,this.$router.replace实现替换当前路由。
两个方法的第一个参数可为string类型的路径,或者可以通过对象将相应参数传入。
通过this.$router.go(n)方法可以实现路由的前进后退,n表示跳转的个数,正数表示前进,负数表示后退。
如果只想实现前进后退可以使用this.$router.forward()(前进一页),以及this.$router.back()(后退一页)。
JavaScript:
// 路由表
const router = new VueRouter({
routes: [
{
path: '/index/:id', // 路由的路径
name: 'index', // 路由名称,可选属性,定义后可以用其实现跳转
component: { // 路由显示的组件
template: '<div>首页:{{$route.params.id}}</div>' // 组件模板
}
},
{
path: '/news/:id/', // 通过路由传参
name: 'news',
component: {
template: '<div>新闻:{{$route.params.id}}</div>'
}
},
{
path: '/user',
name: 'user',
component: {
template: '<div>用户:{{$route.query.userId}}</div>'
}
},
]
})
let vm = new Vue({
el: '#app',
data: {
},
// 将路由添加到Vue中
router,
methods: {
fn1() {
// 通过路由名称跳转,配置params参数。
this.$router.replace({ name: 'index', params: { id: Math.random() } });
},
fn2() {
// 直接跳转路由地址,参数直接带在路径中。
this.$router.push(`/news/${Math.random()}`);
},
fn3() {
// 通过路由地址进行跳转,配置query参数。
this.$router.push({ path: '/user', query: { userId: 321 } });
},
fn4() {
console.log(this.$router)
this.$router.go(1)
},
fn5() {
this.$router.forward()
},
fn6() {
this.$router.go(-1)
},
fn7() {
this.$router.back()
},
}
})
HTML:
<div id="app">
跳转按钮,通过JS跳转<br />
<div class="links">
<input type="button" value="跳转到首页" @click="fn1()">
<input type="button" value="跳转到新闻" @click="fn2()">
<input type="button" value="跳转到用户" @click="fn3()"><br />
<input type="button" value="前进一页" @click="fn4()">
<input type="button" value="前进一页" @click="fn5()">
<input type="button" value="后退一页" @click="fn6()">
<input type="button" value="后退一页" @click="fn7()">
</div>
下面是页面内容<br />
<!-- 路由的内容显示在router-view标签中 -->
<router-view></router-view>
</div>
通过watch实现路由监听
代码示例:/lesson10/02. vue-router 路由监听和守卫.html
通过watch属性设置监听$route变化,达到监听路由跳转的目的。
watch: {
// 监听路由跳转。
$route(newRoute, oldRoute) {
console.log('watch', newRoute, oldRoute)
},
},
导航守卫
代码示例:/lesson10/02. vue-router 路由监听和守卫.html
vue-router支持3种路由守卫,每个守卫参数中的next方法都必须被调用,否则无法进入下一步操作,会阻止路由的跳转,也可以在next方法中传入路由跳转参数string | object,将路由跳转到不同地址。
-
全局守卫
router.beforeEach((to, from, next) => {})
router.beforeResolve((to, from, next) => {})
router.afterEach((to, from) => {}) -
路由守卫
beforeEnter(to, from, next) {} -
组件内守卫
beforeRouteEnter(to, from, next) {}
beforeRouteUpdate(to, from, next) {}
beforeRouteLeave(to, from, next) {}
路由跳转时守卫的运行顺序如下:
-
进入一个新路由
beforeEach => beforeEnter => beforeRouteEnter => beforeResolve => afterEach -
当前路由下跳转,如替换路由参数
beforeEach => beforeRouteUpdate => beforeResolve => afterEach -
离开当前路由
beforeRouteLeave => beforeEach => beforeResolve => afterEach
开发中可以通过不同的守卫处理逻辑。