vue-router封装结构

index.js 文件

import Vue from 'vue'
import VueRouter from "vue-router"
import routes from './routes'
 
Vue.use(VueRouter)
 
// 解決编程式路由住同一地址跳转时会报错的恃观
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) {
        return originalPush.call(this, location, onResolve, onReject)
    } else {
        return originalPush.call(this, location).catch(err => err)
    }
}
// replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject) {
        return originalReplace.call(this, location, onResolve, onReject)
    } else {
        return originalReplace.call(this, location).catch(err => err)
    }
}
const router = new VueRouter({
    routes
})
export default router;

  router文件

// 定义路由路径
const routes = [
    {
        path: '/Main',
        component: () => import('@/views/Main.vue'),
  //子路由设置
        children: [
            {
                path: '/Home',
                component: () => import('@/views/Home.vue')
            },
            {
                path: '/Main',
                component: () => import('@/views/Main.vue')
            },
        ]
    },
    // 例
    // {
    //     path: '/Usre',
    //     component: () => import('@/views/Usre.vue')
    // },
    // 重定向
    {
        path: '/',
        redirect: '/Main'
    }
]

export default routes;

  在main.js 文件挂载

import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from "./router/index.js";    //引入

Vue.config.productionTip = false
Vue.use(ElementUI);

new Vue({
  router,   //挂载
  render: h => h(App),
}).$mount('#app')

  

posted @ 2022-12-06 19:08  web格调  阅读(86)  评论(0编辑  收藏  举报