要在網站建立多語系版本,在vue可以使用vue-i18n來建立各個語言的語言檔來做切換
安裝npm套件
npm install vue-i18n --save
設定i18n
在src內建立一個i18n資料夾存設定檔和各語言的語言檔
檔案路徑:src\i18n\lang.js
中日文設定檔
import Vue from 'vue'
import VueI18n from 'vue-i18n'// 使用VueI18n
Vue.use(VueI18n)// 自訂語言檔
import ja from './ja.js'
import tw from './tw.js'// 使用localStorage取得預設語系
const locale = localStorage.getItem('locale') || "tw";// 建立 VueI18n 實體
const i18n = new VueI18n({
locale,
messages: { ja, tw }
})export default i18n
語言檔案
檔案路徑:src\i18n\tw.js
export default {
__home:'首頁',
}
檔案路徑:src\i18n\ja.js
export default {
__home:'ホーム',
}
設定Main.js
import i18n from './i18n/lang.js'new Vue({
data() {
},
i18n,
render: h => h(App)
}).$mount('#app')
在VUE套用語系
component tempate
<h3 class="home">{{$t("__home")}}</h3><input v-bind:placeholder="$t('__status')"><input :placeholder="$t('__status')">
component script
##使用this.$t("__price"),可以結合Template literals
methods: {
alert() {
console.log(this.$t("__price"))
//結合Template literals
console.log(`${this.$t("__price")}`)
}}
切換語系
在一個component使用localStorage切換中日文
<template>
<div>
<button v-if="this.locale=='tw'" @click="change">日文</button>
<button v-if="this.locale=='ja'" @click="change">中文</button>
</div>
</template>
<script>
export default {
data() {
return{
locale : '',
}
},
mounted() {
this.locale = localStorage.getItem('locale');
},
methods: {
change() {
if(this.locale=="tw"){
localStorage.setItem("locale", "ja");
}else{
localStorage.setItem("locale", "tw");
}
}
}
};
</script