This is 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;
This works fine. But when if someone go to the url and type something else other than these 3 routes I want direct him to a common route says page not found. How to I achieve this using vue.js
for Vue2: 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 matching 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;
for Vue3: check the answer here from Aman https://stackoverflow.com/a/64817425/9128201
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With