在vue项目中安装相关依赖:
npm install i18next i18next-vue i18next-browser-languagedetector
创建i18n.js
文件:
import i18next from 'i18next'
import I18NextVue from 'i18next-vue'
import LanguageDetector from 'i18next-browser-languagedetector'
i18next
.use(LanguageDetector)
.init({
// 初始化i18next
debug: true,
fallbackLng: 'en',
resources: {
en: {
translation: {
// 此处放置翻译内容
}
}
}
});
export default function (app) {
app.use(I18NextVue, {
i18next })
return app
}
在main.js
中导入i18n.js
:
import {
createApp } from 'vue'
import i18n from './i18n'
import App from './App.vue'
i18n(createApp(App)).mount('#app')
对于第一个文本,我们只使用一个简单的welcome
key 来直接调用$t
函数。$t
或多或少与i18next.t
相同。
对于第二个文本,我们使用v-html
指令直接输出真正的HTML。
注意: 在您的网站上动态渲染任意HTML是非常危险的,因为它很容易导致XSS漏洞。只在可信内容上使用v-html
,不要在用户提供的内容上使用。
// TranslationShowCase.vue
<template>
<div class="hello">
<h1>{
{ $t('welcome') }}</h1>
<p v-html="$t('descr')"></p>
</div>
</template>
<script>
export default {
name: 'TranslationShowCase'
}