0

嗨,看看这段代码,如果我在解析新数据时异步设置消息,它不会重新呈现翻译。

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

<div id="app">
  <p>{{ $t("home") }}</p>
</div>

const locale = {
    id: {
    home: 'Beranda'
  },
  en: {
    home: 'Home'
  }
}

const i18n = new VueI18n({
  locale: 'id'
})

new Vue({
  el: '#app',
  i18n,
  created () {
    setTimeout(() => {
    this.$i18n.setLocaleMessage(locale)
  }, 100)
 }
})

更新

我目前的解决方法是定义一个返回 Promise 的方法和保存文本的变量。承诺解决后,我设置翻译。

const locale = {
	id: {
  	home: 'Beranda'
  },
  en: {
  	home: 'Home'
  }
}

const i18n = new VueI18n({
  locale: 'id'
})

new Vue({
	el: '#app',
	i18n,
  data: {
  	text: null
  },
  methods: {
  	getData () {
    	return new Promise(resolve => {
      	setTimeout(() => {
          this.$i18n.setLocaleMessage('id', locale.id)
          this.$i18n.setLocaleMessage('en', locale.en)
          resolve()
        }, 1000)
      })
    }
  },
  created () {
  	this.getData().then(() => {
    	this.text = this.$t('home')
    })
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

<div id="app">
  <p>{{ text }}</p>
</div>

4

1 回答 1

1

查看文档,您需要设置密钥路径。

定义:

const messages = { // keypath
    id: {
    home: 'Beranda'
  },
  en: {
    home: 'Home'
  }
}

并使用messages设置默认语言:

const i18n = new VueI18n({
  locale: 'id', // default locale
  messages // keypath is set
})

如果您使用消息以外的键路径名称:

const translations = { // different keypath constant
    id: {
    home: 'Beranda'
  },
  en: {
    home: 'Home'
  }
}



const i18n = new VueI18n({
  locale: 'id',
  messages: translations // messages now use translations keypath
})


new Vue({
    el: '#app',
    i18n,
  /* created () { // you don't need to set locale here
    setTimeout(() => {
      this.$i18n.setLocaleMessage(locale)
    }, 100)
  } */
})

这是一个工作演示


更新

根据您的评论,异步设置语言环境 - 您可以像这样使用:

const i18n = new VueI18n({
  messages
})

new Vue({
    el: '#app',
    i18n,
  created () {
    setTimeout(() => {
      this.$i18n.locale  = 'id'
    }, 100)
  }
})

演示

于 2018-03-22T04:13:30.577 回答