这是我的简单的route.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实现此目标
答案 0 :(得分:4)
在路由器配置对象的底部,使用路由器通配符语法
{
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;
答案 1 :(得分:2)
如果要重定向到出现url / page-not-found的url,则应创建路径,然后在用户输入不存在的url时重定向到该路径。
您应该将此添加到您的route.js
{ path: '/page-not-found',
components: {
default: PageNotFound //Vue component
},
},
{ path: '*', redirect: '/page-not-found' }
OR
{ path: '/page-not-found',
component: PageNotFound //Vue component
},
{ path: '*', redirect: '/page-not-found' }
答案 2 :(得分:0)
如this答案中所述,*
在Vue 3中不再起作用。只需替换:
{
path: '*',
component: NotFound
}
使用
{
path: '/:pathMatch(.*)*',
component: NotFound
}