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