1.安装
npm install vue-i18n
2.使用配置
import VueI18n from 'vue-i18n'
import zh from './i18n/zh.js'
import en from './i18n/en.js'
import { numberFormats, dateTimeFormats } from './i18n/i18n-config.js'
let lang = (navigator.languages && navigator.languages[0]) || navigator.language //判断浏览器先支持哪个语言
const i18n = new VueI18n({
locale: lang.split('-')[0],
messages: {
zh,
en
},
numberFormats,
dateTimeFormats
})
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
i18n/en.js
export default {
msg: 'hello',
tablecol: {
name:'Name',
age:'Age',
money:'Money',
birthday:'Birthday'
}
}
i18n/zh.js
export default {
msg: '你好',
tablecol: {
name:'姓名',
age:'年龄',
money:'存款',
birthday:'出生日期'
}
}
i18n/zh.js/config.js
export const dateFormat = {
'zh': {
short: {
year: 'numeric', month: '2-digit', day: '2-digit',
}
},
'en': {
short: {
year: 'numeric', month: '2-digit', day: 'numeric',weekday:'long'
}
}
}
export const numberFormat = {
'zh': {
currency: {
style: 'currency',currency:'CNY'
}
},
'en': {
currency: {
style: 'currency',currency:'USD',minimumFractionDigits:3
}
}
}
app.vue
<template>
<div id="app">
<button @click="changeLang()">切换语言</button>
<p>{{$t('msg')}}</p>
<table>
<thead>
<tr>
<th>{{$t('tablecol.name')}}</th>
<th>{{$t('tablecol.age')}}</th>
<th>{{$t('tablecol.money')}}</th>
<th>{{$t('tablecol.birthday')}}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="index">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{$n(item.money,'currency')}}</td>
<td>{{$d(new Date(item.date),'short')}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
list: [
{
name: 'red',
age: 18,
money: 534534545,
date: '2020-2-25'
},
{
name: 'green',
age: 24,
money: 34455000,
date: '2020-2-23'
},
{
name: 'black',
age: 30,
money: 150003443,
date: '2019-11-2'
},
{
name: 'sink',
age: 26,
money: 15000,
date: '2019-6-4'
}
]
}
},
methods: {
changeLang() {
let lang = this.$i18n.locale
this.$i18n.locale = lang==='zh'?'en':'zh'
}
}
}
</script>