在 Nuxt Router 中动态选择组件 [英] Dynamically choose compontent in Nuxt Router

查看:146
本文介绍了在 Nuxt Router 中动态选择组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有语言呈现相同的组件.翻译将在组件内部完成.url 和组件的关系应该是这样的:

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"

我的方法是执行以下操作,不幸的是我找不到访问 pathMatch 的方法.

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

}

推荐答案

我不认为您可以动态解析组件.component: 期望组件实例或 Promise.一旦承诺解决,结果就会被缓存.我可以想象使用导航守卫和手动"切换组件的解决方案,但这需要手动导入视图等.

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.

所以你最好的办法是重写由 nuxt 生成的路径以包含可选的路径段(从 /about/:lang(en|jp)?/about 所以它接受像 /en/about) 这样的路径 - 您的组件然后接收 lang 参数,该参数对于 /about 将为空,否则它将包含语言....

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. meta
  2. 中定义可用的翻译
  3. 用翻译重写页面的路径

在您的页面中:

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

在 Nuxt 配置中(伪 - 未测试)

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

这篇关于在 Nuxt Router 中动态选择组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆