js中如何使用vue-i18n国际化获取相应语言对应字符?

通过 vue-i18n 实现了多语言切换,在template里面已经实现了该功能,但是现在需要在 js 中 获取对应语言的字符,网上找了好久还是没找到,有人知道怎么弄么?

template 里面

{{ $t('message.exchangeCenter.exchangeDate') }}

js里面需要:需要把中文替换成多语言,求解

const exchangeTypes = [
    {id: 1, text: '游戏币'},
    {id: 2, text: '积分'}
];

js中写法:

const exchangeTypes = [
    {id: 1, text: this.$t('xxx')},
    {id: 2, text: this.$t('yyy')}
];

错误提示:
图片描述

阅读 17.2k
8 个回答

文档都是摆设么
http://kazupon.github.io/vue-...

// If using a module system (e.g. via vue-cli), import Vue and VueI18n and then call Vue.use(VueI18n).
// import Vue from 'vue'
// import VueI18n from 'vue-i18n'
//
// Vue.use(VueI18n)

// Ready translated locale messages
const messages = {
  en: {
    message: {
      hello: 'hello world'
    }
  },
  ja: {
    message: {
      hello: 'こんにちは、世界'
    }
  }
}

// Create VueI18n instance with options
const i18n = new VueI18n({
  locale: 'ja', // set locale
  messages, // set locale messages
})

定义好你的字符以后,代码中用
const exchangeTypes = [

{id: 1, text: this.$t('coin')},
{id: 2, text: this.$t('points')}

];

import Vue from 'vue'
import i18n from '@/i18n.js'
const validVue = Vue.extend({ i18n });
new validVue()就是this了
此时new validVue().$t('即可拿到')

换个思路,包起来处理,直接在main.js的new Vue 赋给一个变量,然后再从变量中获取就可以了
如 main.js中
window.vm= new Vue({
// 单独js 中
window.vm.$i18n.t('langkey')

谢谢,问题已经解决了,回来晚了,不好意思。主要问题是这个应该算扩展的 vue 对象,所以this指向的和我们写vue代码里面的this指向是一样的,所以多语言对象只能写到vue实例里面,而不能够直接在js中通过 $t 的方式来获取多语言字符。

题主你好,我也遇到了同样的问题,但是看了你的回答还不是很明白,题主最后怎么解决的呢?谢谢分享^-^

新手上路,请多包涵

怎么实现占位传值呢 就是文本某个位置字符需要动态改变 比如:
message: {

  hello: '你好'{0}
}

就是可以实现 你好lucy \你好Rosi 这样的
新手上路,请多包涵

this.$router.app.$t('chat.chat_message')

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题