vue实现多语言功能

详细步骤

安装vue-i18n

npm install vue-i18n -S

在main.js中引入vue-i18n

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

定义语言文件

const messages = {
  //简体中文
  cn: {
    message: {
      hello: '你好',
      author: '龙的传人'
    }
  },
  //英文
  en: {
    message: {
      hello: 'Hello',
      author: 'Chinese'
    }
  },
  // 繁体中文
  tw: {
    message: {
      hello: '你好',
      author: '龍的傳人'
    }
  }
}

vue-i18n初始化

const i18n = new VueI18n({
  locale: 'cn', // 默认语言
  messages
})

vue-i18n挂载到vue实例

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

vue模板文件中使用

<h1>{{ $t("message.hello") }}</h1>

js中使用

computed:{
    hello(){
       return this.$t("message.hello") + this.$t("message.author");
    } 
}

切换语言

this.$i18n.locale = 'en' // 切换英文

单独定义语言文件 并加载到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
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值