router 路由

发布于:2023-01-09 ⋅ 阅读:(191) ⋅ 点赞:(0)

router 路由

基本格式

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        //路由重定向
        redirect: '/home',
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        // 元数据
        meta: {
            ifShowTabbar: true,
        },
        children: [
            {
                // 子路由的路径要么把/去掉,要么加上父级路由地址
                path: 'popup',
                name: 'MyPopup',
                component: () =>
                    import(
                        /* webpackChunkName: "popup" */ '../views/MyPopup.vue'
                    ),
            },
        ],
    },
    {
        // 子路由的路径要么把/去掉,要么加上父级路由地址
        path: '/productdetail',
        name: 'ProductDetail',
        //懒加载
        component: () =>
            import(
                /* webpackChunkName: "popup" */ '../views/ProductDetail.vue'
            ),
    },
]
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch((err) => err)
}

路由拦截(航守卫:前置导航守卫和后置导航守卫)

// 三个参数

// to 代表即将进入的路由

// from 代表即将离开的路由

// next(),每一个导航守卫必须至少搭配一个 next()

router.beforeEach((to, from, next) => {
    // 想要进入购物车页面,必须有token
    // console.log('to:', to);
    // console.log('from:', from);
    const token = localStorage.getItem('token')
    if (to.path === '/cart') {
        // 此时必须有token
        if (token) {
            next() // 这个next()只针对去住/cart的
        } else {
            // alert("请先登录");
            Vue.prototype.$toast('请先登录')
            // 定时器
            setTimeout(() => {
                next('/user')
            }, 1000)
        }
        return
    }
    next() // 这个是适配所有路由的
})

export default router
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到