How can I access/convert element.varName
string in v-for loop to be passed as variable name to get the current value of this boolean.
In the following case:
<div v-for="(element, index) in elements" :key="index" :>
<div v-html="element.icon"></div>
{{element.name}}
</div>
el1: false,
el2: false,
selected: undefined,
elements: [
{
name: 'element 1',
icon: `<svg>
<path></path>
<rect></rect>
</svg>`,
shortName: 'el1',
varName: this.el1
},
/...
]
How can my included
class be a boolean value instead of the actual string, initially I tried with the shortName
used accessing it as follow:
element.shortName
which didn't work, also tried:
[element.shortName]
as well as:
this[element.shortName]
None of which seems to work, so I tried including the actual reference to that variable by adding it in the object varName: this.el1
, which also didn't work.
What am I doing wrong?
CodePudding user response:
Since you're referencing a data property in other one you should define the second property as computed property :
data(){
return {
el1: false,
el2: false,
selected: undefined,
}
},
computed:{
elements(){
return [
{
name: 'element 1',
icon: `<svg>
<path></path>
<rect></rect>
</svg>`,
shortName: 'el1',
varName: this.el1
}
]
}
}
CodePudding user response:
The reason why varName: this.el1
is not updated inside data
option, is because it's not reactive.
You can read about that in Vue official documentation here.
Back to your question :
Try to assign the whole elements
array in mounted()
life cycle hook. So, that you can access this.el1
.
Demo :
new Vue({
el:"#app",
data: {
el1: false,
el2: true,
elements: []
},
mounted() {
this.elements = [
{
name: 'element 1',
shortName: 'el1',
varName: this.el1
}, {
name: 'element 2',
shortName: 'el2',
varName: this.el2
}
]
}
});
.included {
background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(element, index) in elements" :key="index" :>
{{element.name}}
</div>
</div>