前面所寫的是靜態的國際化切換方式:https://www.cnblogs.com/yoona-lin/p/13594447.html
uni-app系列回顧總結----項目國際化2(翻譯問題與解決方案)總結
現在通過頁面的按鈕進行中英文切換
如圖:
實現:
// main.js
// 國際化模塊
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
if (!uni.getStorageSync('lang')) {
// 設置默認語言
uni.getSystemInfo({
success: (res) => {
uni.setStorageSync('lang', (res.language.indexOf('zh') != -1) ? 'zh_CN' : 'en')
}
})
}
const i18n = new VueI18n({
locale: uni.getStorageSync('lang') || 'zh_CN', // 默認使用中文
messages: {
'en': require('utils/lang/en.js'), // 英文語言包
'zh_CN': require('utils/lang/zh.js') // 中文簡體語言包
}
})
// 導出國際化
export default i18n
Vue.prototype._i18n = i18n
Vue.prototype.$i18nMsg = function(){
return i18n.messages[i18n.locale]
}
App.mpType = 'app';
const app = new Vue({
i18n, // 國際化
...App
});
changeLang.vue
<template> <view class="change-con" @tap="showLangAn" :animation="animation"> <view class="gary-arrow"> <image src="/static/icons/white-arr.png" :animation="animationArrow"></image> </view> <view class="lang-con" @tap="changeLang"> {{changeLangLabel}} </view> </view> </template> <script> export default { data() { return { showLang: false, animation: '', animationArrow: '', changeLangLabel: 'En', // 當前語言 }; }, components: {}, props: {}, // 掛載數據之前先獲取與判斷本地語言類型 beforeMount() { uni.getStorageSync("lang").indexOf('zh') != -1 ? this.changeLangLabel = 'En' : this.changeLangLabel = '中文' }, methods: { changeLang() { if (uni.getStorageSync("lang").indexOf('zh') != -1) { this._i18n.locale = 'en'; this.changeLangLabel = '中文' uni.setStorageSync('lang', 'en') } else { this._i18n.locale = 'zh_CN'; this.changeLangLabel = 'En' uni.setStorageSync('lang', 'zh_CN') } // uni.reLaunch({ // 針對單頁面的點擊切換按鈕,響應到整個項目 // url: '/pages/storeLogin/storeLogin', // success: function(e) { // var page = getCurrentPages().pop(); //跳轉頁面成功之后 // if (!page) return; // console.log(page) // page.onLoad(); //如果頁面存在,則重新刷新頁面 // } // }) }, showLangAn() { this.showLang = !this.showLang var animation = uni.createAnimation({ duration: 600, timingFunction: 'ease', }) var animationArrow = uni.createAnimation({ duration: 400, timingFunction: 'ease', }) this.animation = animation this.animationArrow = animationArrow if (this.showLang) { animation.translate(-45).step() animationArrow.rotate(180).step() } else { animation.translate(0).step() animationArrow.rotate(0).step() } } } }; </script> <style> @import "./changeLang.css"; </style>
changeLang.css
.change-con {
width: 200rpx;
height: 80rpx;
border-radius: 40rpx 0 0 40rpx;
position: fixed;
bottom: 20%;
right: -120rpx;
display: flex;
/* box-shadow: 2rpx 2rpx 10rpx 0 #aaa; */
}
.gary-arrow {
border-radius: 40rpx 0 0 40rpx;
width: 90rpx;
height: 100%;
background-color: #859e5c;
display: flex;
align-items: center;
box-shadow: 2rpx 2rpx 10rpx 0 #aaa;
}
.gary-arrow image {
width: 18rpx;
height: 24rpx;
margin-left: 40rpx;
}
.lang-con {
width: 80rpx;
font-size: 28rpx;
background-color: #98b369;
display: flex;
align-items: center;
justify-content: center;
color: #FFFFFF;
}
調用: