赞
踩
i18n
,即多国语言的配置依赖,使用它可以很方便的给不同的国家的人员查看自己的项目,并将其切换为自己国家的语种。
这波属于是和国际接轨了[赞]
那么接下来就和大家说一下如何配置
首先,需要安装vue-i18n插件,使用命令
npm install vue-i18n --save
安装。
在main.js中引入vue-i18n插件并创建实例:
import Vue from 'vue' import VueI18n from 'vue-i18n' import messages from './i18n' Vue.use(VueI18n) const i18n = new VueI18n({ locale: 'zh', // 默认语言 messages, // 引入语言文件 fallbackLocale: 'en' // 没有对应语言时的默认语言 }) new Vue({ i18n, render: h => h(App) }).$mount('#app')
其中,messages是引入的语言文件,由我们自己自定义
在项目中新建messages.js
,然后按照如下格式:
const messages = { en: { welcome: 'Welcome to Vue', home: 'Home', about: 'About', contact: 'Contact Us' }, zh: { welcome: '欢迎使用Vue', home: '主页', about: '关于我们', contact: '联系我们' } } export default messages
为了在页面使用它,我们需要在翻译的地方使用$t
方法即可
按照如下示例:
<template>
<div>
{{$t('welcome')}}
</div>
</template>
注意:welcome
是我们上方messages.js
自定义的属性值
另外,为了实现方便的语种切换,可以在组件中添加下拉框或按钮等切换语言的功能,并通过i18n.locale方法切换语言:
<template> <div> <button @click="setLocale('en')">English</button> <button @click="setLocale('zh')">中文</button> {{$t('welcome')}} </div> </template> <script> export default { methods: { setLocale (locale) { this.$i18n.locale = locale } } } </script>
以上代码实现了在组件中添加两个按钮来切换语言。通过点击按钮时调用setLocale方法,然后设置i18n.locale的值,即可实现语言切换。
以上就是vue项目配置i18n的过程
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。