二十五、路由钩子与异步请求
官方文档:钩子函数及参数 — Vue.js
回顾十五、Vue生命周期中的两张图,其中就涉及到了钩子。
1.什么是钩子函数
钩子函数
:钩子函数是在一个事件触发的时候,在系统级捕获到了他,然后做一些操作。一段用以处理系统消息的程序。“钩子”就是在某个阶段给你一个做某些处理的机会。-
- 是个函数,在系统消息触发时被系统调用
-
- 不是用户自己触发的
-
钩子函数的名称是确定的,当系统消息触发,自动会调用。
例如
react
的componentWillUpdate
函数,用户只需要编写componentWillUpdate
的函数体,当组件状态改变要更新时,系统就会调用componentWillUpdate
。
常见的钩子函数:
- react的生命周期函数
- vue的生命周期函数
- vue的自定义指令
- ……
解释来源于:理解什么是钩子函数
2.路由钩子
beforeRouteEnter
:在进入路由前执行beforeRouteLeave
:在离开路由前执行beforeRouteUpdate
: Vue2.2 新增,用于相同路由组件的的参数更新
是
时机函数
,在页面加载前,可以在这两个函数里面做一些事情, 比如发送异步请求
。类似
过滤器
,或者拦截器
的环绕。它们是和
data
,methods
平级的:beforeRouteLeave(to, from, next) { next() }, beforeRouteEnter(to, from, next) { next() }, beforeRouteUpdate(to, from, next) { next() }, data: {}, method: {}
2.1 参数说明
to
路由将要跳转的路径信息from
路径跳转前的路径信息next
路由的控制参数,必须存在一种next
方法next()
跳入下一个页面,next('/path')
改变路由的跳转方向,跳到下一个页面next(false)
返回原来的页面next((vm) => {})
只能在beforeRouteEnter
中可用,vm
是组件实例
// 两个钩子函数,类似过滤器或拦截器的环绕
beforeRouteEnter: (to, from, next) => {
console.log('进入路由之前...');
next() // 必写
},
beforeRouteLeave: (to, from, next) => {
console.log('离开路由之前...')
next() // 必写
}
到控制台试试 进入、离开路由前 是否会打印日志信息?
3. 在钩子函数中使用异步请求
官方文档:vue-axios|axios中文网
- 安装
Axios
:
npm install --save vue-axios
main.js
引入Axios
:
import axios from 'axios'
import VueAxios from 'vue-axios'
//使用
Vue.use(VueAxios, axios)
- 准备测试数据,新建
static/mock/data.json
:
静态数据存放的位置:
static
文件夹下的mock
文件夹
{
"name": "MelodyJerry",
"url": "https://melodyhub.ltd/",
"page": 1,
"isNonProfit": true,
"address": {
"street": "广州",
"city": "广东",
"country": "中国"
},
"links": [
{
"name": "博客园",
"url": "https://www.cnblogs.com/melodyjerry/"
},
{
"name": "GitHub",
"url": "melodyhub.ltd"
},
{
"name": "Gitee",
"url": "https://melodyjerry.gitee.io/"
}
]
}
- 运行
npm run dev
,访问http://localhost:8080/static/mock/data.json
,获取json数据:
- 在
beforeRouteEnter
中进行异步请求:
<script>
export default {
name: "UserProfile",
//传递参数
props: ['id'],
beforeRouteEnter (to, from, next) {
console.log("进入路由之前...");
//加载数据
next(vm => { //发送异步请求并放行
vm.getDatd(); //进入路由之前执行getData方法
}); //必写
},
beforeRouteLeave (to, from, next) {
console.log("进入路由之后...");
next(); //必写
},
methods: {
getDatd: function () {
this.axios({
methods: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (respone) {
console.log(respone);
})
}
},
}
</script>
<style scoped>
</style>
- 运行
npm run dev
,打开控制台:
参考文章
[0] Vue.js 官方文档
[1] 关于template标签用法总结(含vue中的用法总结)
[2] Vue2 模板template的四种写法总结(很重要)
[7] 理解什么是钩子函数
[8] vue组件独享守卫钩子函数参数详解(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)