【问题标题】:How can I use vue-i18n in a Vue web component?如何在 Vue Web 组件中使用 vue-i18n?
【发布时间】:2019-04-19 20:25:22
【问题描述】:

我正在使用 vue-cli 3 和 --target wc 选项创建一个 Vue Web 组件。我还需要组件使用 vue-i18n 插件,这需要将一些选项传递给主 Vue 实例,如下所示:

new Vue({
    i18n: new VueI18n({ ... ])
    ...
})

在常规的 Vue 应用程序中这很好,因为我控制了主 Vue 实例的构造。但是,当构建为 web 组件时,主 Vue 对象的构建是由 vue-web-component-wrapper 生成的,我没有看到任何明显的方式来影响它。

如何在我的 Web 组件中使用 vue-18n 插件?

【问题讨论】:

  • 我认为“本地组件注册”可能会解决您的问题。看看这个:stackoverflow.com/questions/48066237/…
  • @JimB.,我在组件注册方面没有问题。 vue-i18n 安装说明要求我向根 Vue vm 添加一个新对象。在 Web 组件中,唯一的“根”虚拟机是入口组件,在那里添加 VueI18n 对象似乎不起作用。

标签: vue.js vuejs2 web-component vue-i18n


【解决方案1】:

i18n 插件需要在“入口”组件(即构成 Web 组件基础的组件)而不是根组件上初始化。

但即便如此,所有消息都在入口组件上定义很重要。在子组件上定义消息,无论是直接在组件中还是使用<i18n> 元素,都会有效地覆盖入口组件中的 vue-i18n 配置,并导致该子组件使用默认语言 en-US。

这是一个简单的工作示例:

入口组件

<template>
  <div>
    <p>{{ $t('hello') }}</p>
    <child-component />
  </div>
</template>

<script>
import ChildComponent from "./child.vue"
import Vue from "vue"
import VueI18n from "vue-i18n"
Vue.use(VueI18n)

export default {
  name: "App",
  i18n: new VueI18n({
    locale: 'ja',
    messages: {
      en: {
        hello: "hello in en",
        test: "test in en"
      },
      ja: {
        hello: "hello in ja",
        test: "test in ja"
      },
    }
  }),
  components: { ChildComponent }
};
</script>

子组件

<template>
  <div>{{ $t("test") }}</div>
</template>

<script>
export default {
  name: "child-component"
};
</script>

【讨论】:

    【解决方案2】:

    @tctimmeh 解决方案的问题在于 i18n plugin 需要实际传递到 new Vue 构造函数中,但是在使用 web components wrapper 时,我们无法访问 new Vue,因为它位于包装器库中 因此,幸运地感谢这个 PR https://github.com/kazupon/vue-i18n/pull/420/commits/13ed0488caf70ab454ffd5cb2affa36ec31c4c50 我们可以用VueI18n的瞬间在实例化之前扩展Vue对象

    import Vue from 'vue'
    import wrap from '@vue/web-component-wrapper'
    import VueI18n from 'vue-i18n';
    
    
    const Component = {
      // any component options
    }
    
    const i18n = new VueI18n({
        locale: 'en',
    });
    
    const VueExtended = Vue.extend({ i18n });
    
    const CustomElement = wrap(VueExtended, Component)
    
    window.customElements.define('my-element', CustomElement)
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 2021-03-27
      • 2020-07-16
      • 2020-09-08
      • 2022-12-01
      • 2022-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多