【Vue】22.vue组件级路由钩子函数(beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave)
一.beforeRouteEnter(to, from, next)beforeRouteEnter函数内部this是undefined,这是因为在执行路由钩子函数beforeRouteEnter时候,组件还没有创建出来;先执行beforeRouteEnter,再执行组件周期钩子函数beforeCreate。我们可以通过next获取组件实例对象,如:next((vm) => {});参数..
·
一.beforeRouteEnter(to, from, next)
beforeRouteEnter函数内部this是undefined,这是因为在执行路由钩子函数beforeRouteEnter时候,组件还没有创建出来;先执行beforeRouteEnter,再执行组件周期钩子函数beforeCreate。我们可以通过next获取组件实例对象,如:next((vm) => {});参数vm就是组件的实例对象。
// 当进入组件之前,执行beforeRoutEnter路由钩子函数
beforeRouteEnter(to, from, next) {
console.log('beforeRouteEnter');
console.log(`to.fullPath : ${JSON.stringify(to.fullPath)}`);
console.log(`from.fullPath : ${JSON.stringify(from.fullPath)}`);
console.log(this);
next((vm) => {
vm.name = '我被改变了';
console.log(this);
});
},
这里要注意的一点儿是next这个回调函数在mounted钩子函数之后才会执行。
二.beforeRouteUpate(to,from,next)
子路由切换的时候会执行beforeRouteUpate(to, from, next)钩子函数。
beforeRouteUpdate(to, from, next) {
console.log('my beforeRouteUpdate');
console.log(`to.fullPath : ${JSON.stringify(to.fullPath)}`);
console.log(`from.fullPath : ${JSON.stringify(from.fullPath)}`);
next();
},
三.beforeRouteLeave(to,from,next)
页面路由切换,跳转页面离开的时候触发
// 离开组件的时候触发
beforeRouteLeave(to, from, next) {
console.log('my beforeRouteLeave');
next();
},
完整demo代码:
<template>
<div id="report-parent-list">
<div class="report-head">
<router-link @click.native="clickRouterTabValid"
to="/reportList/reportListValid"
replace
class="link">有效报告</router-link>
<router-link @click.native="clickRouterTabInvalid"
to="/reportList/reportListInvalid"
replace
class="link">失效报告</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
name: 'ReportList',
};
},
created() {
console.log(`created: ${this.name}`);
},
mounted() {
console.log(`mounted: ${this.name}`);
},
beforeUpdate() {
console.log(`beforeUpdate: ${this.name}`);
},
updated() {
console.log(`updated: ${this.name}`);
},
methods: {
clickRouterTabValid() {
// eslint-disable-next-line
_hmt.push(['_trackEvent', 'click', 'click', '点击有效报告tab', 10]);
},
clickRouterTabInvalid() {
// eslint-disable-next-line
_hmt.push(['_trackEvent', 'click', 'click', '点击无效报告tab', 10]);
},
},
// 当进入组件之前,执行beforeRoutEnter路由钩子函数
beforeRouteEnter(to, from, next) {
console.log('beforeRouteEnter');
console.log(`to.fullPath : ${JSON.stringify(to.fullPath)}`);
console.log(`from.fullPath : ${JSON.stringify(from.fullPath)}`);
console.log(this);
next((vm) => {
vm.name = '我被改变了';
console.log(this);
});
},
beforeRouteUpdate(to, from, next) {
console.log('my beforeRouteUpdate');
console.log(`to.fullPath : ${JSON.stringify(to.fullPath)}`);
console.log(`from.fullPath : ${JSON.stringify(from.fullPath)}`);
next();
},
beforeRouteLeave(to, from, next) {
console.log('my beforeRouteLeave');
next();
},
};
</script>
更多推荐
已为社区贡献20条内容
所有评论(0)