本文主要是介绍vue多语言插件vue-i18n,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装vue-i18n
npm install vue-i18n -S
使用
1.在main.js中引入vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
2.vue-i18n初始化
const i18n = new VueI18n({locale: 'cn', // 默认语言messages
})
3.vue-i18n挂载到vue实例
new Vue({el: '#app',router,i18n, // i18ntemplate: '<App/>',components: { App }
})
4.定义语言文件,使用
const messages = {//简体中文cn: {message: {hello: '你好',author: '龙的传人'}},//英文en: {message: {hello: 'Hello',author: 'Chinese'}},// 繁体中文tw: {message: {hello: '你好',author: '龍的傳人'}}
}
- vue模板文件中使用
<h1>{{ $t("message.hello") }}</h1>
- js中使用
computed:{hello(){return this.$t("message.hello") + this.$t("message.author");}
}
5.切换语言
切换英文
this.$i18n.locale = 'en'
6.单独定义语言文件 并加载到vue-i18n初始化中
// cn.js
export default {message: {hello: '你好',author: '龙的传人'}
}
// en.js
export default {message: {hello: 'Hello',author: 'Chinese'}
}
import cnlang from './lang/cn.js'
import enlang from './lang/en.js'
const i18n = new VueI18n({locale: 'cn', // 默认语言messages: {'cn': cnlang,'en': enlang}
})
引用来自文章
http://www.imooc.com/article/262994
这篇关于vue多语言插件vue-i18n的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!