如果找不到路由,Vue.js 如何重定向到公共路由

新手上路,请多包涵

这是 我的简单 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 实现此目的

原文由 margherita pizza 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 594
2 个回答

对于 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

原文由 mostafa tourad 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 {
    path: '*',
    component: NotFound
}

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

原文由 Aman Dalmia 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题