vue用i18n实现多语言支持(国际化)
vue-i18n是用于多语言适配的vue插件,主要用于前端项目的国际化应用。个简单的例子:<!DOCTYPE html><html><head><meta charset="utf-8"><title>getting started&
vue-i18n是用于多语言适配的vue插件,主要用于前端项目的国际化应用。
个简单的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>getting started</title>
<script src="../../node_modules/vue/dist/vue.min.js"></script>
<script src="../../dist/vue-i18n.min.js"></script>
</head>
<body>
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
<script>
var messages = {
en: {
message: {
hello: 'hello world'
}
},
ja: {
message: {
hello: 'こんにちは、世界'
}
}
}
Vue.use(VueI18n)
var i18n = new VueI18n({
locale: 'ja',
messages: messages
})
new Vue({ i18n: i18n }).$mount('#app')
</script>
</body>
</html>
我们可以看到vue-i18n的使用非常的简单,我们只需要定义好对应的语言包messages,然后设置一个默认语言类型locale,然后实例化出一个i18n对象并传入我们的vue实例就可以愉快的使用起来
ps:插值表达式中的$t就是vue-i18n暴露给用户的API
<template>
<div>
<h1>{{$t('message.hello')}}{{$i18n.locale}}</h1>
<div>{{$i18n.messages}}</div>
<div></div>
<el-button type="primary" @click="open">{{$t('btn.text')}}</el-button>
</div>
</template>
<script>
import { getProjectList } from "api/basicInfoService/project/index";
export default {
data() {
return {
projectOptions: null
}
},
created() {
getProjectList().then(response => {
this.projectOptions = response;
console.log(response)
this.$i18n.mergeLocaleMessage('zh', this.projectOptions)
}) .catch((err) => {
this.$message.error(this.$t('message.hello') + ':' + err.message)
});
},
methods: {
}
}
</script>
$i18n.locale来选择性显示相应的语言 项目用的是vue-cli框架,i18n.locale是自动监听变化的
这里this.$i18n.messages就是多语言切换的数据来源
vue-i18n的mergeLocaleMessage方法 新加载的数据合并到全局
源码地址 https://github.com/kazupon/vue-i18n
原理解析 https://hachijiang.github.io/vue-i18n%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/
更多推荐
所有评论(0)