Dynamically choose compontent in Nuxt Router

一世执手 提交于 2020-02-05 03:56:24

问题


I would like to render the same component for all languages. The translation will be done inside the component. The url and component relationship should look like so:

pseudocode:
browserurl: "/blogpost_1"
nuxtcomponent: "blogpost_1"

browserurl: "/en/blogpost_1"
nuxtcomponent: "blogpost_1"

browserurl: "/randompage"
nuxtcomponent: "randompage"

browserurl: "/en/randompage"
nuxtcomponent: "randompage"

My approach was to do the following, unfortunately i cant find a way to access pathMatch.

router: {
   extendRoutes(routes, resolve){
   routes.push({
     path: 'en/*',
     component: resolve(__dirname, '/' + somehow.access.pathMatch )
})
}

}


回答1:


I don't think you can resolve component dynamically. component: expects component instance or Promise. Once the promise resolves, result is cached. I can imagine solution using navigation guards and switching components "by hand" but that would require to import views by hand etc.

So your best bet is to rewrite paths generated by nuxt to include optional path segment (from /about to /:lang(en|jp)?/about so it accepts paths like /en/about) - your component then receives lang parameter which will be empty for /about otherwise it will contain language....

  1. Define available translations in meta
  2. Rewrite the paths of pages with translations

In your page:

<script>
export default {
  meta: {
    translations: ['en', 'jp']
  }
}
</script>

In Nuxt config (pseudo - not tested)

router: {
    extendRoutes(routes, resolve) {
        const routesWithTranslation = routes.filter(i => i.meta.translations && i.meta.translations.length > 0);

        routesWithTranslation.forEach(route => {
            const segment = `/:lang(${route.meta.translations.join("|")})?`
            route.path = segment + route.path           
        })
}


来源:https://stackoverflow.com/questions/59392801/dynamically-choose-compontent-in-nuxt-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!