Vue国际化-i18n
效果图
安装
yarn add vue-i18n
使用
1.在main.js中引入i18n。
import Vue
from 'vue';
import VueI18n
from "vue-i18n";
import App
from './App.vue';
import router
from './router';
import store
from './store';
Vue
.config
.productionTip
= false;
Vue
.use(VueI18n
);
const i18n
= new VueI18n({
locale
: 'zh',
messages
: {
'zh': require('./assets/lang/zh'),
'en': require('./assets/lang/en')
}
})
new Vue({
router
,
store
,
i18n
,
render
: h
=> h(App
)
}).$mount('#app')
2.语言包内需要定义好项目中用到的语句。
(1).zh.js
module
.exports
= {
message
: {
aboutMsg
: '这是相关页面',
zh
: '中文',
en
: '英文'
}
}
(2).en.js
module
.exports
= {
message
: {
aboutMsg
: 'This is an about page',
zh
: 'Chinese',
en
: 'English'
}
}
3.页面中使用
<template>
<div class="about">
<h1>{{ $t('message.aboutMsg') }}
</h1>
<input type="radio" name="lang" id="zh" value="zh" v-model="lang" /><label for="lang">{{
$t('message.zh')
}}
</label>
<input type="radio" name="lang" id="en" value="en" v-model="lang" /><label for="lang">{{
$t('message.en')
}}
</label>
</div>
</template>
<script>
export default {
data: () => ({
msg: 'message.about',
lang: 'zh'
}),
watch: {
lang(newValue) {
this.$i18n.locale = newValue;
}
},
mounted() {}
};
</script>
页面中使用只需要$t('message.变量名'),注意给$t传递的参数是字符串。
vue国际化其他方法及优缺点
图片来自于:https://blog.csdn.net/qq_42269433/article/details/90902247?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf