路由中的钩子函数
这里首先明确一下,什么是钩子函数。
钩子的概念源自于 windows
的消息处理机制,通过设置钩子,应用程序可以对所有的消息时间进行拦截,然后执行钩子函数,对消息进行想要的处理方式。
比如,vue.js 中的生命周期函数。
所以,作为 vue.js
的重要组成部分之一,vue-router
中也同样设置了钩子函数。路由的钩子选项可以配置在路由配置文件中,也可以写在我们的组件模板中。
比如,在路由文件中进行配置:
import Vue from 'vue';
import Router from 'vue-router';
import Hello from '@/components/HelloWorld'
import Params from '@/components/Params';
import Hi1 from '@/components/Hi1.vue';
import Error from '@/components/404.vue';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
alias: '/home',
},
{
path: '/params/:newsId(\\d+)/:newsTitle',
component: Params,
beforeEnter: (to, from, next) => {
console.log(to);
console.log(from);
next();
}
},
]
})
这里的 beforeEnter
就是路由钩子函数。我们来看一下输出的结果:
from
这个对象包含的是跳转前路由中所包含的信息,比如:
- name
- params
- matched
等等。
to
这个对象包含的跳转到的路由所包含的信息,比如:
- name
- params
- path
- matched
等等。
next()
的意思允许进行跳转。其实就是这个钩子函数拦截了跳转这个行为,我们可以根据要求进行重定向,允许跳转等等。
比如,点击这个 <a>
标签后跳转至 /
路径:
next({path: '\'});
我们一般在模板中写离开这个路由地址的钩子函数
接下来我们在模板中写路由钩子函数
<template>
<div>
<h3>
{{msg}}
</h3>
<p>newsId: {{ $route.params.newsId }}</p>
<p>newTitle: {{ $route.params.newsTitle }}</p>
</div>
</template>
<script>
export default {
name: 'Params',
data() {
return {
msg: `Params pages`,
}
},
beforeRouteEnter (to, from, next) {
console.log(to);
console.log(from);
console.log('准备进入 params 路由模板');
next();
},
beforeRouteLeave(to, from, next) {
console.log(to);
console.log(from);
console.log('准备离开 params 路由模板');
next();
}
}
</script>
直接在 <script>
标签中写即可,记得加上 before
,结果为: