vue.js - 如何在 Vue Web 组件中使用 vue-i18n?

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

我正在使用 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 插件?

最佳答案

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>

关于vue.js - 如何在 Vue Web 组件中使用 vue-i18n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341395/

相关文章:

javascript - 如何在Vue Js中通过axios调出查询

javascript - 从观察者返回结果 - Vue JS

vue.js - vuex 如何像 redux 一样改变商店中的多个属性?

css - 如何使用适当的特异性来设置 :root without ! important 的样式

polymer - 焦点和模糊事件的事件重定向

.net - vue 和 dotnet 的 cors 问题

vue.js - Vuetify 在现有组件中使用 Font Awesome 图标

javascript - router-link 无法在 Vuejs 中正确创建链接

javascript - 微前端/Web 组件/Vue 路由器错误 : Uncaught TypeError: Cannot redefine property: $router

javascript - Firebase 函数将日期时间存储为 map