// Vue 3 + Vue I18n 示例代码
// 1. 安装 vue-i18n
// npm install vue-i18n@next
import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import App from './App.vue';
// 2. 创建 i18n 实例
const i18n = createI18n({
locale: 'en', // 设置默认语言为英语
messages: {
en: {
message: {
hello: 'hello world'
}
},
zh: {
message: {
hello: '你好,世界'
}
}
}
});
// 3. 创建 Vue 应用并挂载 i18n
const app = createApp(App);
app.use(i18n);
app.mount('#app');
// 4. 在组件中使用 $t 方法来获取翻译内容
// 例如在 App.vue 中:
/*
<template>
<div>
<p>{{ $t('message.hello') }}</p>
<button @click="changeLocale">切换语言</button>
</div>
</template>
<script>
export default {
methods: {
changeLocale() {
this.$i18n.locale = this.$i18n.locale === 'en' ? 'zh' : 'en';
}
}
}
</script>
*/
vue-i18n
,确保使用的是与 Vue 3 兼容的版本。createI18n
函数创建一个国际化实例,并设置默认语言和多语言的消息内容。$t
方法来获取翻译后的文本内容,并可以通过修改 locale
来切换语言。下一篇:vue2 watch监听
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站