Vue.js how to redirect to a common route if route isn't found
At the bottom of your router configuration object use the router wild card syntax
{
path :'*',
component:NotFound
}
this will direct the user to the component NotFound if there is no match route at the top , so your router config can be something like this
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;
If you want to redirect to url where appear url/page-not-found, you should create the path and then redirect to it when the user enter an url that not exists.
You should add this to your routes.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' }