步驟
1. 在相對根目錄 utils/lang 的文件夾創建js的語言文件。當然,也可以根據實際情況,在其他目錄下。這里,使用了兩種語言,en-US (英文)和zh-CN(簡體中文)。

2. 打開main.js引入 vue-i18n 和語言包,並根據需要默認其中一種語言。
import Vue from 'vue' import App from './App' import enUS from 'utils/lang/en-US.js'; // 英文語言文件 import zhCN from 'utils/lang/zh-CN.js'; // 中文語言文件 import VueI18n from 'vue-i18n' Vue.use(VueI18n) Vue.config.productionTip = false const i18n = new VueI18n({ locale: 'en-US', messages: { 'en-US': enUS, 'zh-CN': zhCN } }) Vue.prototype._i18n = i18n App.mpType = 'app' const app = new Vue({ i18n, ...App }) app.$mount()
3. 當頁面中需要引用語言欄時,調用$t方法。
uniapp 不支持在取值表達式中直接調方法,因此,$t方法不可用,所以通過計算屬性的方式。
因此,要調用語言欄的頁面(如index.vue)代碼如下:
1 <template> 2 <view > 3 <view>{{ i18n.invite }}</view> 4 <view>{{ i18n.game }}</view> 5 </view> 6 </template> 7 8 <script> 9 export default { 10 data() { 11 return { 12 } 13 }, 14 computed: { 15 i18n() { 16 return this.$t('index') 17 } 18 }, 19 } 20 </script> 21 22 <style> 23 24 </style>
擴展:上面的方式,是否可用定義一個變量,然后獲取它的方法?答:可以,但不推薦這么使用。具體的原因,是因為計算屬性,有自己合適的應用場景。不推薦的代碼示例如下:
1 <template> 2 <view > 3 <view>{{ i18n.invite }}</view> 4 <view>{{ i18n.game }}</view> 5 </view> 6 </template> 7 8 <script> 9 export default { 10 data() { 11 return { 12 i18n : null, 13 } 14 }, 15 computed: { 16 17 }, 18 onLoad:function(){ 19 this.i18n = this.$t('index'); 20 } 21 22 } 23 </script> 24 25 <style> 26 27 </style>
切換語言
以上代碼,已經讓全局包含_i18n。.vue頁面切換語言方法為 this._i18n.locale = "zh-CN"; 。
參考網址
- https://www.cnblogs.com/yoona-lin/p/13705543.html
- uniapp與vue-i18n實現國際化多語言:https://ask.dcloud.net.cn/article/35102
