我正在构建 Vue 应用程序而不使用 npm。由于涉及 npm 的指南太多,我无法正确遵循它们。所以,我只包括这样的脚本:
<script src="/js/bluebird.min.js"></script>
<script src="/js/vue.js"></script>
<script src="/js/vue-i18n.js"></script>
<script src="/js/axios.min.js"></script>
<script src="/js/components.js"></script>
<script src="/js/app.js"></script>
现在我正在尝试通过从 json 文件加载按钮来显示按钮列表。该文件包含带有按钮信息的对象数组,包括不同语言的文本。所以,现在我不明白如何让 vue-i18n 从那个文件中加载消息。基本代码:
<buttons-list inline-template>
<div class="buttons-list">
<big-button inline-template
:class="[button.position, button.number]"
v-for="button in buttons"
:key="button.id"
:button="button">
<div class="big-button">{{ $t(button.text) }}</div>
</big-button>
</div>
</buttons-list>
按钮列表组件代码:
Vue.component('buttons-list', {
data: function() {
return {
buttons: []
}
},
created: function() {
this.loadButtons()
},
methods: {
loadButtons: function() {
const list = this;
axios.get('/json/buttons.json')
.then(function(response) {
list.buttons = response.data
})
}
}
})
这里我在创建组件时读取 json 文件,所以当创建 bigButton 时,button
属性将包含所有必需的信息。bigButton 组件代码:
Vue.component('big-button', {
data: function() {
return {
text: ''
}
},
props: ['button'],
created: function() {
this.$i18n.setLocaleMessage('en', this.button.messages.en)
this.$i18n.setLocaleMessage('ru', this.button.messages.ru)
},
i18n: {
messages: {}
}
})
在这里,在created
函数中,我尝试将实例设置i18n.messages
为来自 json 文件的数据。基本上,这是可行的,除了它将messages
所有按钮重置为当前数据,最终所有按钮都具有相同的最后一个按钮的文本。是否可以在 vue-i18n 中使用组件实例?或者还有其他我想念的方式吗?
解决方案
我已将bigButton
组件代码更改为:
Vue.component('big-button', {
data: function() {
return {
text: ''
}
},
props: {
button: {
type: Object,
default: function() {return {}}
},
},
created: function() {
this.$i18n.setLocaleMessage('en', this.button.messages.en)
this.$i18n.setLocaleMessage('ru', this.button.messages.ru)
},
i18n: {
//i18n stops working when this block removed
}
})
它奏效了!