路由单独钩子(router独享守卫)
使用:在路由配置中单独加入钩子,在src/router/index.js中使用,代码如下:
1、创建one.vue组件:
<div>
<h1>我是首页组件中的 子组件 -- one.vue</h1>
</div>
2、在src/router/index.js中, 在one组件中单独加 钩子:
import one from '@/views/one.vue'
Vue.use(VueRouter)
const routes = [
// 重定向
{
path:'/home', // 从这个地方开始 能够访问到下面的地址
redirect:'/' // 从上面的 访问到这里
},
{
path: '/', // 访问路径
name:'home',
component: HomeView,
// 嵌套路由 -- 子路由
children:[
{
path:'/home/one',
component:one,
// 在路由中 单独添加钩子 -- 路由单独钩子(router独享守卫)
beforeEnter:(to, from, next)=>{
console.log('进入前执行');
next(); // 放行
}
}
]
},
3、在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>
<!-- 路由占位符 --- 添加后 我们才能在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>
预览效果: