【问题标题】:Vue.js how to redirect to a common route if route isn't found如果找不到路由,Vue.js如何重定向到公共路由
【发布时间】:2018-11-30 08:18:46
【问题描述】:

这是我的简单 routes.js 文件

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

import welcome from './components/welcome.vue';
import restaurant from './components/restaurant.vue';
import eatMe from './components/eat-me.vue';

const routes = [{
    path: '/',
    component: welcome,
    name: welcome
}, {
    path: '/restaurant',
    component: restaurant
}, {
    path: '/eat-me',
    component: eatMe
}]

const router = new VueRouter({
    routes,
    mode: 'history'
});

export default router;

这很好用。但是,如果有人转到该 url 并输入除这 3 条路线以外的其他内容时,我希望将他引导至一条公共路线,则表示 找不到页面。如何使用 vue.js 实现这一目标

【问题讨论】:

  • { path: '*', component: something }{ path: '*', redirect: '/' } 你会认为这是一个如此常见的用例,他们会在基本示例中或至少在文档中的某个地方使用它,但他们所拥有的只是一个链接为此:文档中的github.com/pillarjs/path-to-regexp#parameters(来自高级匹配模式)。我确定你的路线顺序很重要,把你的后备路线放在最后。
  • 非常感谢它的工作!

标签: vue.js vuejs2 vue-router


【解决方案1】:

对于 Vue2:在路由器配置对象的底部使用路由器通配符语法

{
    path :'*',
    component:NotFound
}

如果顶部没有匹配的路由,这会将用户引导到组件 NotFound,因此您的路由器配置可以是这样的

import Vue from 'vue';
import VueRouter from 'vue-router';
import welcome from './components/welcome.vue';
import restaurant from './components/restaurant.vue';
import eatMe from './components/eat-me.vue';
import NotFound from '../components/NotFound'
Vue.use(VueRouter);

const routes = [{
    path: '/',
    component: welcome,
    name: welcome
}, {
    path: '/restaurant',
    component: restaurant
}, {
    path: '/eat-me',
    component: eatMe
}, {
    path :'*',
    component:NotFound
  }
]

const router = new VueRouter({
    routes,
    mode: 'history'
});

export default router;

对于 Vue3:在此处查看 Aman 的答案 https://stackoverflow.com/a/64817425/9128201

【讨论】:

  • 对于 Vue 3,请参考 Aman Dalmia 的回答
  • @elliotching 我做到了,谢谢
【解决方案2】:

如果你想重定向到出现 url/page-not-found 的 url,你应该创建路径,然后在用户输入不存在的 url 时重定向到它。

你应该把它添加到你的 routes.js 中

{ path: '/page-not-found',
    components: {
        default: PageNotFound //Vue component
    },
},
{ path: '*', redirect: '/page-not-found' }

{ path: '/page-not-found',
    component: PageNotFound //Vue component
},
{ path: '*', redirect: '/page-not-found' }

【讨论】:

    【解决方案3】:

    正如this 回答中提到的,* 不再适用于 Vue 3。只需替换:

    {
        path: '*',
        component: NotFound
    }
    

    {
        path: '/:pathMatch(.*)*',
        component: NotFound
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 2019-08-01
      • 2020-10-17
      • 2021-01-26
      • 1970-01-01
      • 2013-03-28
      • 2021-11-17
      相关资源
      最近更新 更多