如何在Vue 3构建的Web Component中使用vue-i18n(Options API场景)
Vue 3 Web Component 内部集成vue-i18n解决方案
前置依赖
先安装适配Vue3的vue-i18n版本:npm install vue-i18n@9
组件内配置方案
Vue3中vue-i18n不再支持组件选项中直接传入i18n实例的写法,你可以在根组件的beforeCreate钩子中完成i18n实例初始化和手动挂载,同时兼容两种使用场景:
import { createI18n } from 'vue-i18n' import ChildComponent from './ChildComponent.vue' // 多语言配置,可单独抽成文件引入 const messages = { zh: { greeting: '你好,欢迎使用' }, en: { greeting: 'Hello, welcome' } } export default { name: "custom-compo", components: { ChildComponent }, beforeCreate() { // 初始化i18n实例 const i18n = createI18n({ locale: 'zh', // 默认语言,可根据需求动态调整 fallbackLocale: 'en', messages }) // 挂载i18n相关方法到当前组件实例,和全局注册用法完全一致 this.$i18n = i18n.global this.$t = i18n.global.t this.$tc = i18n.global.tc this.$te = i18n.global.te this.$d = i18n.global.d this.$n = i18n.global.n // 向当前应用上下文注入全局属性,兼容子组件调用i18n能力 this.$.appContext.config.globalProperties.$i18n = i18n.global this.$.appContext.config.globalProperties.$t = i18n.global.t this.$.appContext.config.globalProperties.$tc = i18n.global.tc this.$.appContext.config.globalProperties.$te = i18n.global.te this.$.appContext.config.globalProperties.$d = i18n.global.d this.$.appContext.config.globalProperties.$n = i18n.global.n }, // 其余data、methods、生命周期等配置正常编写即可 data() { return {} } }
兼容性说明
- 作为Web Component打包后在普通页面使用:i18n实例在组件自身初始化阶段完成挂载,不依赖全局Vue实例,不会出现上下文丢失问题,所有方法可正常调用
- 本地执行
npm run serve运行项目:组件初始化时会自动向当前应用的全局属性中注入i18n相关能力,不需要在main.js中做任何额外配置,项目内所有组件都可以正常使用i18n功能
内容的提问来源于stack exchange,提问作者DieSeL
相关产品推荐
相关产品推荐

