Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js how to redirect to a common route if route isn't found

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

like image 695
Pathum Kalhan Avatar asked Jun 21 '18 05:06

Pathum Kalhan


1 Answers

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

like image 112
mostafa tourad Avatar answered Sep 20 '22 07:09

mostafa tourad