1、安装
npm install vue-i18n --save
2、注入 vue 实例中,项目中实现调用 api 和 模板语法
// main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router/index' import VueI18n from 'vue-i18n'; Vue.config.productionTip = false; Vue.use(VueI18n); /* eslint-disable no-new */ router.beforeEach((to, from, next) => { if ((to.query.lang !== 'cn' && to.query.lang !== 'en')) { if (from.query.lang === 'cn' || from.query.lang === 'en') { to.query.lang = from.query.lang } else { to.query.lang = 'en' } // to.query.profile = from.query.profile; // to.query._ = Date.parse(new Date()) next({ path: to.path, name: to.name, query: to.query, params: to.params, }) }else{ next() } }); const lang = window.location.search.includes('lang=cn') ? 'cn' : (window.location.search.includes('lang=en') ? 'en' : 'jp') ; // console.log('ffffffffff', lang); const messages = { cn: { hello: '好好学习,天天向上!' }, en: { hello: 'good good study, day day up!' }, jp: { hello: 'よく勉強して、毎日向上します!' } }; const i18n = new VueI18n({ locale: lang, // 语言标识 messages, }); new Vue({ el: '#app', router, i18n, components: { App }, template: '<App/>' });
3、在页面中应用
<template> <div class="hello"> <!-- <h1>{{ msg }}</h1>--> <h1 style="font-size: 16px; text-align: center;">{{ $t("hello") }}</h1> <h1 style="font-size: 16px; text-align: center;">{{ $t("title") }}</h1> </div> </template> <script> export default { name: 'HelloWorld', i18n:{ messages:{ en: { title: 'Sport Brands', nike: 'Nike', adi: 'Adidas', nb: 'New Banlance', ln: 'LI Ning' }, cn: { title: '运动品牌', nike: '耐克', adi: '阿迪达斯', nb: '新百伦', ln: '李宁' }, } }, data () { return { msg: 'Welcome to Your Vue.js App' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
4、实际效果