如何调用Vue数据中的对象作为项的值



假设我想将这个{{ $t('index-p1') }}添加到title的值中。

items: [
{
icon: 'mdi-apps',
title: 'Welcome',
to: '/'
},

我将其用于i18n,{{ $t('index-p1') }}包含的数据存储在JSON文件中。如果我在Vue模板文件中使用它,它会很好地工作,但在数据中不使用,我不记得如何完成这一部分。

items应定义为计算属性,并使用this:访问$t

computed:{
items(){
return [
{
icon: 'mdi-apps',
title: this.$t('welcome'),
to: '/'
}
]
}
}

您可以使用计算属性并使用this.$t:调用它

const messages = {
en: {
message: {
hello: 'hello world'
}
},
fr: {
message: {
hello: 'bonjour'
}
}
}
const i18n = new VueI18n({
locale: 'en', 
messages, 
})
new Vue({
i18n,
computed: {
text() { return this.$t("message.hello")}
},
methods: {
setLang(lang) {
i18n.locale = lang
}
}
}).$mount('#demo')
items: [
{
icon: 'mdi-apps',
title: 'Welcome',
to: '/'
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-i18n/8.15.5/vue-i18n.min.js"></script>
<div id="demo">
<button @click="setLang('fr')">fr</button>
<button @click="setLang('en')">en</button>
<p>{{ $t("message.hello") }}</p>
{{ text }}
</div>

最新更新