- {{$t(item.name)}}
1.首先下载vue-i18n
npm i vue-18n --save
2.在项目根目录新建文件夹(自己命名)i18n.config.js,写如下代码
注意:小编在vue.config.js里面配置了路径别名,@l指向src/lang目录
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Element from 'element-ui'
const zh =require("@l/zh.js")
const en =require("@l/en.js")
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from 'element-ui/lib/locale/lang/en'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
//this.$i18n.locale // 通过切换locale的值来实现语言切换
silentTranslationWarn: true,
messages: {
'zh-CN':Object.assign(zh, zhLocale), // 中文语言包
'en-US':Object.assign(en, enLocale) // 英文语言包
}
})
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value)
})
export default i18n // 暴露i18n
3.新建语言资源文件(第一个是zh.js,第二个是en.js)
export const m= {
index:'首页',
product:'产品中心',
aboutUs:'关于我们',
contactUs:'联系我们',
phone:'24小时服务热线',
}
export const m={
index:'index',
product:'productCenter',
aboutUs:'aboutUs',
contactUs:'contactUs',
phone:'Phone',
}
4.把vue-i18n挂在到实例上
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import '../src/assets/css/reset.css'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import i18n from '../i18n.config.js'
Vue.config.productionTip = false
Vue.use(ElementUI);
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount('#app')
5.在组件中使用
{{$t("m.phone")}}
如果是v-for循环的数据:
- {{$t(item.name)}}