1. 程式人生 > 其它 >vue引用簡單封裝vue-i18n

vue引用簡單封裝vue-i18n

1.安裝外掛(以下的寫法是vue3.0的寫法)

  npm install vue-i18n

2.先放截圖,再放程式碼

 

 

 

 

 

 

 

 

 

 

 3.程式碼:

src/lang/en.js

module.exports = {
loginPage:{
login: 'login',
register: 'register',
home:'Home',
about:'About'
}
}

 

 

src/lang/zh.js

module.exports = {
loginPage:{
login: '登入',
register: '註冊',
home:'主頁',
about:'關於'
}
}

 

 

src/lang/index.js

import { createI18n } from 'vue-i18n'
import cn from './zh.js'
import en from './en.js'
const messages = {
en: {
...en,
},
cn: {
...cn,
}
};
const i18n = createI18n({
locale: localStorage.lang || 'cn',
messages,
});
export default i18n;

 

 

src/lang/util.js

export const locale = (lang) => {
if (lang) {
localStorage.setItem('lang', lang);
} else if (lang === null) {
localStorage.removeItem('lang');
} else {
lang = localStorage.getItem('lang');
}
return lang;
}

 

 

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import i18n from './lang/index.js'
import {locale} from './lang/util'

const app = createApp(App)
app.config.globalProperties.$locale = locale
app
.use(i18n)
.use(store)
.use(router)
.mount('#app')

 

 

頁面呼叫

<template>
<div class="hello">
<div class="ab-menu">
<div @click="setLang('cn')">簡體中文</div>
<div @click="setLang('en')">English</div>
</div>
<div>{{$t('loginPage.login')}}</div>
</div>
</template>

<script>
export default{
mounted() {
console.log(this.$locale('cn'))
},
methods: {
setLang(lang) {
if (lang !== this.$i18n.locale) {
this.$locale(lang);
location.reload(); // 頁面重新載入
}
},
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>