How to redirect to a router with params in vue-routers

Viewed 1108

I want to organize my vue router like this: (xxx.com is my domain)

xxx.com/ -> redirect to xxx.com/en/home

xxx.com/:lang -> redirect to xxx.com/:lang/home (:lang is a param meaning language)

xxx.com/:lang/home -> home page of :lang

xxx.com/:lang/result/:date -> result page of a date

xxx.com/:lang/result -> redirect to xxx.com/:lang/result/current_date (current_date can be regarded as new Date())

Below is my vue-router config

const router = new VueRouter({
    mode: 'history',
    routes: [{
        path: '/',
        redirect: '/en/home',
    },{
        path: '/:lang',
        name: 'lang',
        component: () => import("./Frame.vue"),
        redirect: {name: 'home'},
        children: [{
            path: 'home',
            name: 'home',
            component: () => import("./components/Home.vue")
        },{
            path: 'result/:date',
            name: 'result',
            component: () => import("./components/ResultDay.vue")
        },{
            path: 'result',
            redirect: {name: 'result', params: {date: new Date()}},
        }]
    }]
});

But it cannot redirect from xxx.com/en/result to xxx.com/en/result/current_date. JS console shows an error as "[vue-router] missing param for named route "result": Expected "lang" to be defined"

So how can I pass the param lang to the "result" router ?

1 Answers
mode: 'history',
    routes: [{
        path: '/',
       //  redirect: '/en/home',
       // set default to lang base url 
        redirect: () => {
            return '/en'
        }
    },{
        path: '/:lang',
        name: 'lang',
        // component: () => import("./Frame.vue"),
        component: {
            template: '',  // if you have no special codes in Frame.vue
        },
        // redirect: {name: 'home'},
        redirect: to => ({
            path: '/'+to.params.lang+'/home',  // user lang passed by :lang
        }),
        children: [{
            path: 'home',
            name: 'home',
            component: () => import("./components/Home.vue")
        },{
            path: 'result/:date',
            name: 'result',
            component: () => import("./components/ResultDay.vue")
        },{
            path: 'result',
            redirect: {name: 'result', params: {date: new Date()}},
        }]
    }]
Related