在vue3使用vue-i18n@9
vue-i18n@9文档地址Home | Vue I18n (intlify.dev)
vue-i18n是vue的国际化插件, 它可以轻松将一些本地化功能集成到Vue.js项目中.
Get Started
下载并引入
-
先简单搭建一个vue3 demo
vue create <project name>
-
安装vue-i18n
npm install vue-i18n@next # or yarn add vue-i18n@next
import { createApp } from 'vue' import { createI18n } from 'vue-i18n/index'; // /index import App from './App.vue' const app = createApp(App); const i18n = createI18n({ legacy: false, // 使用CompotitionAPI必须添加这条. locale: 'zh-CN', // 首选语言 fallbackLocale: "en-US", // 备选语言 }) app.use(i18n); app.mount('#app');
引入i18n有一个warning
-
博客编写于2022年2月4日
暂时无法使用
<script setup>
写法
局部 - 只作用于当前组件
// HelloWorld组件
<<template>
<div class="hello-world">
<!-- t是从执行useI18n函数解构得到函数, hello是自己定义的变量 -->
<p>{
{
t("hello") }}</p>
<p>{
{
t("home.title") }}</p>
<p>{
{
hello }}</p>
</div>
</template>
<script>
import {
computed } from "vue";
import {
useI18n } from "vue-i18n/index"; //导入并使用
export default {
setup() {
const {
t } = useI18n({
// 传入messages对象, 里面分别是需要被安排的文字. "zh-CN" - 中文, "en-US" - 英文, 两个对象的key必须完全一致.
messages: {
"zh-CN": {
hello: "你好,世界",
home: {
title: "欢迎来到地球",
},
},
"en-US": {
hello: "hello, world",
home: {
title: "Welcome to the Earth",
},
},
},
});
// t是一个函数,能在mustache(模板语法)中使用,当然也能在setup函数任何地方使用
const hello = computed(() => t("hello"));
return {
t,
hello,
};
},
};
</script>
<style scoped>
</style>
<p>{
{
t("hello") }}</p>
<p>{
{
t("home.title") }}</p>
<p>{
{
hello }}</p>
<p>你好, 世界</p>
<p>欢迎来到地球</p>
<p>你好, 世界</p>
全局 - 所有组件都能使用
- 给
useI18n
函数传入useScope: "global"
后再传入的messages
即是全局变量.
// App.vue组件
// 当然也可以是其他任何组件, 写在这里符合vue的 单向数据流 原则, 包括切换语言按钮.
<template>
<HelloWorld />
<HelloChina></HelloChina>
<!-- 给用户提供切换语言按钮 -->
<button @click="changeLang">中/English</button>
<!-- 如果需要多语言切换 -->
<select v-model