组件内钩子(组件内路由守卫)
使用:在路由组件内定义钩子函数:
-
beforeRouteEnter:进入页面前调用
-
beforeRouteUpdate (2.2 新增):(路由更新钩子) 页面路由改变时调用,一般需要带参数
-
beforeRouteLeave:离开页面调用
// 组件内钩子(组件内路由守卫)
// 进入页面前迪调用
beforeRouteEnter(to, from, next){
console.log('进入页面前调用 beforeRouteEnter该钩子函数');
// console.log(to);
next()
},
// 离开页面调用
beforeRouteLeave(to, from, next){
console.log('离开页面调用 beforeRouteLeave该钩子函数');
// console.log(to);
next()
},
// 页面路由改变(又叫路由更新)时调用
// 在组件复用时,且组件上的 参数不同 才会被调用 当你点击超链接的时候 在跳转的时候,
// 因为参数发生了变化,所以我们认为 此刻路由更新了 下面这个钩子哈哈苏 在此时会被调用
beforeRouteUpdate(to, from, next){
console.log('页面路由改变时调用 beforeRouteUpdate该钩子函数');
console.log(to.params);
next()
},
完整例子,代码如下所示:
创建two.vue组件:
<template>
<div>
<h1>我是 two.vue 组件</h1>
</div>
</template>
<script>
export default {
name: 'two',
data() {
return {
num:520,
msg:'小李子是憨憨'
};
},
mounted() {
},
// 组件内钩子(组件内路由守卫)
// 进入页面前迪调用
beforeRouteEnter(to, from, next){
console.log('进入页面前调用 beforeRouteEnter该钩子函数');
// console.log(to);
next()
},
// 离开页面调用
beforeRouteLeave(to, from, next){
console.log('离开页面调用 beforeRouteLeave该钩子函数');
// console.log(to);
next()
},
// 页面路由改变(又叫路由更新)时调用
// 在组件复用时,且组件上的 参数不同 才会被调用 当你点击超链接的时候 在跳转的时候,
// 因为参数发生了变化,所以我们认为 此刻路由更新了 下面这个钩子哈哈苏 在此时会被调用
beforeRouteUpdate(to, from, next){
console.log('页面路由改变时调用 beforeRouteUpdate该钩子函数');
console.log(to.params);
next()
},
methods: {
},
};
</script>
<style lang="scss" scoped>
</style>
接着,到路由配置文件中 router---index.js 配置路由:
{
// /:id通过这种方式 在路径是哪个写一个 动态传参
path:'/home/two/:id',
component:()=>import('@/views/two.vue')
}
在HomeView.vue组件中设置,如下所示:
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<!-- 路由跳转标签 -->
<router-link to="/home/one">我要访问 one组件</router-link>  
<!-- 复用 参数不同 -->
<router-link to="/home/two/250">我要访问 two组件</router-link>  
<router-link to="/home/two/520">我要访问 two组件</router-link>  
<router-link to="/home/two/1314">我要访问 two组件</router-link>  
<router-link to="/home/two/999">我要访问 two组件</router-link>  
<!-- 路由占位符 --- 添加后 我们才能在home视图层中看到 one.vue 里的内容 -->
<router-view></router-view>
</div>
</template>
<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
components: {
// HelloWorld
}
}
</script>
预览效果: