Reputation: 152
Is there any way to add a variable in a v-if statement in my situation?
I have a variable in data language = 'en'
, a big json with some data in multiple language (it's called message).
The message json looks like:
"message": {
"en": 1,
"es": 2
}
and then I want to code like this.
<span v-if="message.lang">some data</span>
It works this way
<span v-if="message.en">some data</span>
It doesn't work
<span v-if="message[lang]">some data</span>
but this way I cannot use the lang variable. Can anyone help me with my problem?
Upvotes: 1
Views: 3312
Reputation: 3529
Don't change your message object. Simply use the lang
property as computed property that returns a defined property currentLang="en"
in data and dynamically change that property. For example:
data: {
currentLang: 'en',
...
}
On the respective button click call a method like:
onLangChange(event){
this.currentLang = "es";
}
So whenever currentLang
changes its gonna trigger computed of lang
:
computed: {
lang: function () {
return this.currentLang;
}
}
And then it will update the html accordingly:
<span v-if="message[lang]">some data</span>
Upvotes: 3
Reputation: 500
Did you defined the lang
property in your data ?
<template>
<h1>{{ message[lang] }}</h1>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
lang: 'en',
message: {
en: 'foo bar',
fr: 'machin truc'
}
}
}
};
</script>
I think you should have a look at https://github.com/kazupon/vue-i18n
Upvotes: 1