margherita pizza
margherita pizza

Reputation: 7145

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

Upvotes: 15

Views: 26845

Answers (3)

mostafa tourad
mostafa tourad

Reputation: 4388

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

Upvotes: 25

Aman Dalmia
Aman Dalmia

Reputation: 406

As mentioned in this answer, * doesn't work anymore for Vue 3. Simply replace:

{
    path: '*',
    component: NotFound
}

with

{
    path: '/:pathMatch(.*)*',
    component: NotFound
}

Upvotes: 21

AythaNzt
AythaNzt

Reputation: 1057

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' }

Upvotes: 12

Related Questions