这是my simple routes.js file.

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上输入这三条路由以外的其他内容,我想让他找到一条公共路由,比如page not found.如何使用vue实现这一点.js

推荐答案

for 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;

for Vue3:在这里查看Aman的答案

Vue.js相关问答推荐

如何默认打开一个v-list-group?

在移动版本中使用标准的 v-data-table

如何 for each 动态创建的按钮/文本字段设置唯一变量?

何时将代码拆分为 Nuxt 中的组件?

有没有办法初始化一个保留初始 HTML 的 Vue 对象

Webpack 导入的模块不是函数

在组件之间共享 websocket 连接

VueJS:如何在组件数据属性中引用 this.$store

如何在 vue 的 scss 中使用深度 Select 器

可以同时使用 Tailwind css 和 Bootstrap 4 吗?

Vuetify - 如何保持第一个扩展面板默认打开,如果我打开另一个面板,其他面板应该关闭?

在 SASS 中使用 Vuetify 类

Vue 和 TypeScript 所需的props

使用 VueJS 在 v-for 中转换

Laravel Blade 模板将数据传递给 Vue JS 组件

[Vue 警告]:无效的props:propsscrollThreshold的类型判断失败.期望的数字,得到字符串

加载时焦点文本框上的 Vue.js

Vue Js如何在单个文件模板中使用mixins?

如何使用 Vue Test utils 测试输入是否聚焦?

偶数行格式化