1、安裝
$ npm i vue-i18n
2恕刘、配置
1、創(chuàng)建 utils/i18n.js
2、編輯 utils/i18n.js
// i18n.js
import {
createI18n
} from 'vue-i18n';
const messages = {
cn: {
country: '中文',
common: {
login: '登錄',
toVip: '升級VIP'
},
loginPage: {
mobile: '手機短信',
wechatLogin: '使用微信掃一掃登錄',
privacyPolicy: '隱私政策'
}
},
en: {
country: 'English',
common: {},
loginPage: {}
},
tc: {
country: '中文繁體',
},
mys: {
country: 'Bahasa Melayu',
},
sa: {
country: '???????',
}
};
const i18n = createI18n({
locale: 'cn', // set default locale
fallbackLocale: 'en',
messages, // set locale messages
});
export default {
i18n, // vue綁定用
messages // 手動選擇國際化需要使用
};
3矮湘、引入
main.js
import i18nObj from './utils/i18n.js';
const app = createApp(App);
app.use(i18nObj.i18n);
-
yourComponent.vue
國際化手動選擇代碼
// setup
import i18nObj from '../utils/i18n.js'
const Countries = reactive([]) // 語種列表,用來下拉讓用戶選擇
const currCountry = ref('中文')
// 初始化語種口糕、并緩存
for (let c in i18nObj.messages) {
Countries.push(c)
if (!localStorage.getItem('country')) {
localStorage.setItem('country', '中文')
} else {
currCountry.value = localStorage.getItem('country')
}
}
function changeLocale(newLocale) {
locale.value = newLocale;
}
function commandClick(key) {
changeLocale(key)
currCountry.value = i18nObj.messages[key].country
localStorage.setItem('country', i18nObj.messages[key].country)
}
<el-dropdown @command="commandClick" size="small" type="primary">
<el-text>{{ currCountry }}</el-text>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item v-for="c in Countries" :key="c" :command="c">
{{ i18nObj.messages[c].country }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
4缅阳、 yourComponent.vue
國際化引入數(shù)據
<div>{{ $t('cuntry') }}<div>
<div>{{ $t('loginPage.mobile') }}<div>
如果值為數(shù)組,不拿直接訪問數(shù)組,需要依次取出下標