欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > vue >内容正文

vue

vue-router之路由钩子(八)

发布时间:2025/3/8 vue 31 豆豆
生活随笔 收集整理的这篇文章主要介绍了 vue-router之路由钩子(八) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

路由钩子,即导航钩子,其实就是路由拦截器,vue-router一共有三类:

  • 全局钩子:最常用

  • 路由单独钩子

  • 组件内钩子

  • 1、全局钩子

    在src/router/index.js中使用,代码如下:

    // 定义路由配置const router = new VueRouter({ ... })// 全局路由拦截-进入页面前执行router.beforeEach((to, from, next) => {// 这里可以加入全局登陆判断// 继续执行next();});// 全局后置钩子-常用于结束动画等router.afterEach(() => {//不接受next});export default router;

    每个钩子方法接收三个参数:
    to: Route : 即将要进入的目标 [路由对象]
    from: Route : 当前导航正要离开的路由
    next: Function : 继续执行函数

    • next():继续执行

    • next(false):中断当前的导航。

    • next(‘/‘) 或 next({ path: ‘/‘ }):跳转新页面,常用于登陆失效跳转登陆

    2、路由单独钩子

    使用:在路由配置中单独加入钩子,在src/router/index.js中使用,代码如下:

    {path:'/home/one', // 子页面1component: One,// 路由内钩子beforeEnter: (to, from, next) => {console.log('进入前执行');next();}}

    3、组件内钩子

    使用:在路由组件内定义钩子函数:

    • beforeRouteEnter:进入页面前调用

    • beforeRouteUpdate (2.2 新增):页面路由改变时调用,一般需要带参数

    • beforeRouteLeave:离开页面调用

    任意找一页面,编写如下代码:

    <script>export default {name: 'Two',data () {return {msg: 'Hi, I am Two Page!'}},// 进入页面前调用beforeRouteEnter(to, from, next) {console.log('进入enter路由钩子')next()},// 离开页面调用beforeRouteLeave(to,from, next){console.log('进入leave路由钩子')next()},// 页面路由改变时调用beforeRouteUpdate(to, from, next) {console.log('进入update路由钩子')console.log(to.params.id)next()}}</script>


    转载于:https://blog.51cto.com/4547985/2390810

    总结

    以上是生活随笔为你收集整理的vue-router之路由钩子(八)的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。