原文:https://vuedose.tips/create-a-i18n-plugin-with-composition-api-in-vuejs-3/
在 Vue.js 3 中用 Composition API 编写插件的方式,和传统上通过一个 install
函数并被 Vue.use(plugin)
使用并不一样;后者通常会在 Vue 原型上做操作或扩展。
但在 Composition API 中的组件,操控是不可能操控的,且 i18n 组件要以一种 inject-provide 模式进行编码。举例来说,可以像这样创建一个 i18n 插件:
// i18nPlugin.js
import { ref, provide, inject } from "@vue/composition-api";
const createI18n = config => ({
locale: ref(config.locale),
messages: config.messages,
$t(key) {
return this.messages[this.locale.value][key];
}
});
const i18nSymbol = Symbol();
export function provideI18n(i18nConfig) {
const i18n = createI18n(i18nConfig);
provide(i18nSymbol, i18n);
}
export function useI18n() {
const i18n = inject(i18nSymbol);
if (!i18n) throw new Error("No i18n provided!!!");
return i18n;
}
如你所见,函数 provide
和 inject
被用来创建插件实例,并用一种依赖注入机制将其持有。
注意我们在 locale 上使用了 ref
,因为要用到其反应式特性。
如果你对 i18n 或 Composition API 尚不了解,可以先阅读:
而后,必须在应用中通过调用 provideI18n
函数,用正确的配置初始化该插件。这一般是在 App.vue 根组件中进行的:
<script>
import { provideI18n } from "./i18nPlugin";
import HelloWorld from "./HelloWorld";
export default {
components: { HelloWorld },
setup() {
provideI18n({
locale: "en",
messages: {
en: {
hello_world: "Hello world"
},
es: {
hello_world: "Hola mundo"
}
}
});
}
};
</script>
最终,在任何需要国际化的组件中,通过在 setup
入口函数中调用 useI18n
函数,来实现 inject。创建如下的 HelloWorld.vue 组件:
<template>
<div>
<h2>{{ i18n.$t('hello_world') }}</h2>
</div>
</template>
<script>
import { useI18n } from "./i18nPlugin";
export default {
setup() {
const i18n = useI18n();
return { i18n };
}
};
</script>
但是...不能更改语言还差着很大点儿意思嘛~ 在之前的代码中添入这个功能:
<template>
<div>
<h2>{{ i18n.$t('hello_world') }}</h2>
<button @click="switchLanguage">Switch language</button>
</div>
</template>
<script>
import { useI18n } from "./i18nPlugin";
export default {
setup() {
const i18n = useI18n();
const switchLanguage = () => {
const locale = i18n.locale.value === "en" ? "es" : "en";
i18n.locale.value = locale;
};
return {
i18n,
switchLanguage
};
}
};
</script>
仅仅通过在一个按钮上调用 switchLanguage
函数,就实现了这个特性。
这就是全部要做的了。我之所以喜爱 Composition API ,就是因其易于通过清晰的模式,开发可预测与可维护的代码。
--End--
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有