1.在router.ts内,只有根路径使用 '/' 就可以,二级路由以及三级都写在children下,二级路由可以配置'/',配置后是也是一个根路由,和'/'是同级的

router/index.ts

import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';

import home from '../views/home'
import product from '../views/product'
import scheme from '../views/scheme'
import together from '../views/together'
import ours from '../views/ours'

import dataAnalysis from '../views/prodectMng/dataAnalysis'
Vue.use(VueRouter);

/*ts解决重新请求路由/报错*/
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return (originalPush.call(this, location)as any).catch(err => err)
};
const routes: Array<RouteConfig> = [
  {
      path: '/',
      name: 'index',
      redirect:'home',// 根路由重定向到 home
      component: () => import(/* webpackChunkName: "about" */ '../views/index.vue'),
      children:[
          {path:'home',name:'home',component:home},
          {path:'product',name:'product',component:product,children:[
                  // default child route with empty string as alias.
                  {path:'dataAnalysis',name:'dataAnalysis',component:dataAnalysis,alias:''},
                  {path:'attractCenter',name:'attractCenter',component:attractCenter},
              ]},
          {path:'scheme',name:'scheme',component:scheme},
          {path:'together',name:'together',component:together},
          {path:'ours',name:'ours',component:ours}

      ]
  },
    {path: '*',redirect: '/home'}
];

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to:any,from:any,next:any)=>{
    // console.log(to)
    Vue.prototype.Cancel.forEach(cancel => {
        // console.log(cancel)
        cancel();
    });
    Vue.prototype.Cancel = [];
  next();
});

export default router;

如上,二级和三级都没有使用'/',使用后访问这些页面都是直接localhost:8082/#/dataAnalysis

现在访问localhost:8082/#/product/dataAnalysis

2.在使用编程式导航时,也就是router.push()时,里面的路由名称一定要加上/,否则会找不到对应的路由,也就是在路由跳转时采用完整路径的方式

this.$router.push('/product/dataAnalysis');
this.$router.push('/home');

以下方法在跳转时会直接拼接在上个路由后面
this.$router.push('product/dataAnalysis');// 错误
this.$router.push('home');// 错误 

错误的跳转方法会导致你访问的路由发生错误找不到,当从localhost:8082/#/product/dataAnalysis跳转到home时,你想要的结果是localhost:8082/#/home,然而如果使用上面错误的跳转情况,结果就是localhost:8082/#/product/dataAnalysis/home,如果你恰好有这个页面,而且还能点击路由跳转,他会继续在后面拼接localhost:8082/#/product/dataAnalysis/home/.../...../.... ,你在view内使用<router-link to="">也是同样的,routerlink 也是router.push的实现

当然上面错误只是仅对当前采用的嵌套路由模式,如果你全部采用根路由,push时怎么样都可以,错误的方法也不在是错误

 

 

趟坑前进中。。。记录每一个坑

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Logo

前往低代码交流专区

更多推荐