vue中i18n的安裝與幾種使用方式詳解
介紹 Vue I18n 是 Vue.js 的國際化插件。它可以輕松地將一些本地化功能集成到你的 Vue.js 應用程序中。
vue中i18n安裝
1、在項目中安裝i18n
npm install vue-i18n
2、如果在一個模塊系統(tǒng)中使用它,你必須通過 Vue.use() 明確地安裝 vue-i18n:
import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n)
項目中的使用
我們在項目中最多的是通過標簽切換來轉換語言的顯示,
locale是控制顯示語言的配置
this.$i18n.locale=‘cn’
下面是完整的代碼
文件夾路徑

創(chuàng)建i18n文件夾放入你需要的語言和index.js文件
index代碼
import VueI18n from 'vue-i18n'
import Vue from 'vue'
//引入element的語言包
import localeLib from 'element-ui/lib/locale' //本地
import enLocale from "element-ui/lib/locale/lang/en"; //英文
import zhLocale from "element-ui/lib/locale/lang/zh-CN"; //中文
// 引入需要語言包也可是js文件,export default拋出語言包的對象
import en from './lang/saas-en.json'
import zh from'./lang/saas-zh-CN.json'
Vue.use(VueI18n)
//獲取本地選擇的語言
var lang =
Cookie.get("bx_user_lang") ||
navigator.language ||
navigator.userLanguage ||
"en";
const i18n = new VueI18n({
locale: lang, // 語言標識
fallbackLocale: 'zh-CN',
messages: {
en: Object.assign(en, enLocale),
"zh-CN": Object.assign(zh, zhLocale)
}
})
// 設置語言
localeLib.i18n((key, value) => i18n.t(key, value))
export default i18n
main.js
import i18n from './i18n/i18n';
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
i18n, //很重要,別忘記
components: { App },
template: '<App/>'
})
使用方式 組件里使用
<template>
<div>
<span>{{$t('message.text')}}</span> //使用方式1
<p>{{title}}</p> //使用方式3
<span v-text="$t('message.text')"></span>//使用方式2
<el-select @change="langChange" placeholder="請選擇語言">
<el-option v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div>
</template>
<script>
export default {
data () {
return {
title:this.$t('message.text'),
options:[
{ value: 'cn', label: '中文' },
{ value: 'en', label: 'English' }
]
}
},
methods: {
//語言切換
langChange(e){
localStorage.setItem('lang',e);
this.$i18n.locale = e;
window.location.reload()
}
}
}
</script>
使用方式js
vue3中在頁面js使用有點不同 $t() 會掛載到proxy上,在js中使用proxy.$t()
// 刪除人員
const delMenu = async (row) => {
await deletePerson(row)
proxy.$message.success(proxy.$t("person.message.success.delete"))
}
如果組件里沒有proxy呢
先定義一個轉換的方法translateTitle()
創(chuàng)建一個i18n.ts,寫入下面代碼,返回一個translateTitle
import i18n from "@/i18n";
export function translateTitle(title: string) {
const { t, te } = i18n.global
if (te(`${title}`)) return t(`${title}`)
return title;
}組件中使用,方法還是一樣,是用自己定義的方法translateText,代替了proxy.$t.代碼如下
import { translateText } from "@/utils/i18n" //在組件中引入
import { ElMessage } from 'element-plus'
const tots=()=>{
ElMessage.success(translateText('person.message.success'))
}
最后附上官方文檔的地址
https://kazupon.github.io/vue-i18n/zh/
總結
到此這篇關于vue中i18n的安裝與幾種使用方式的文章就介紹到這了,更多相關vue中i18n安裝與使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue中this.$refs獲取為undefined的原因和解決辦法(this.$refs.屬性為undefined原因
vue+springmvc導出excel數(shù)據(jù)的實現(xiàn)代碼
vue中使用elementUI自定義校驗及點擊提交不生效問題解決辦法
ant design中upload組件上傳大文件,顯示進度條進度的實例

