Vue i18n多语言设置(可在js内引用)

本文详细介绍了如何在Vue项目中实现多语言支持,包括安装i18n依赖包、配置i18n对象、在main.js中注册i18n对象、在组件中使用$t方法以及在非模板js文件中正确调用多语言资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装依赖包npm install i18n --save

2.创建一个单独i18n.js,用于创建一个i18n对象,后续整个项目统一使用该对象。

import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) 

let lang = localStorage.lang?localStorage.lang:'zh_CN';
const i18n = new VueI18n({ 
  locale: lang, 
  fallbackLocale: 'zh_CN', 
  messages: {
    en_US:require('./en_US.json'),
    zh_CN:require('./zh_CN.json'),
    zh_TW:require('./zh_TW.json'),
  }
})
export default i18n;

3.在main.js内将该对象注册到原型链上

import i18n from './utils/locale/i18n';

new Vue({
	el: '#app',
	router:jxrouter,
  store:store,
  i18n,
	template: '<App/>',
	components: { App }
}).$mount('#app')

4.在页面上引用

<div class="base-descr-header">
   <img src="./../../assets/svg/portal/app_detail_descr.svg"/>
   <div>{{$t('iframeView.tool.appdetail.description')}}</div>
</div>

5.Vue template js内引用

 this.tipsInfo=this.$i18n.t('iframeView.tool.appdetail.description');

6.在单独js文件Vue template以外应用,先在js内引入i18n.js,然后通过函数的模式返回数据,务必使用函数返回的模式,因为使用一般属性对象,在编译一次后,后面更改语言,不会自动刷新。

import i18n from './../locale/i18n';
const Menu={
  getMenu(){
    return [{
      id:"web_5d10b86bc3535a56e87d3d4f",
      imagepath:require("./../../assets/svg/home/home.svg"),
      routerPath:"/home",
      objectId:"home",
      menuType:"DEFAULT",
      name:i18n.t("portal.header.menu.home"),
    }]
  }
}

export default Menu;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值