In order to dynamically construct a series of CSS style classes based on the toolName property in the JSON data using Vue 2, I tried to use a computed property to bind them to the existing span with a class of panel-icon. However, when attempting to save the results of the for loop to a variable and return it, only one result is returned instead of the four that were expected. The goal is to have the CSS class match the tool name displayed in the v-for loop.
HTML:
<div class="container" id="lab">
<a class="panel-block" v-for="tool in tools">
<span class="panel-icon" :class="style">
<i class="fas fa-book" aria-hidden="true"></i>
</span>
{{ tool.toolName }}
</a>
</div>
CSS:
.icon--bulma {
color: hsl(171, 100%, 41%);
}
.icon--jgthms {
color: hsl(204, 86%, 53%);
}
.icon--marksheet {
color: hsl(48, 100%, 67%);
}
.icon--minireset {
color: hsl(348, 100%, 61%);
}
Vue.js:
new Vue({
el: '#lab',
data: {
tools: [
{
toolName: 'bulma'
},
{
toolName: 'marksheet'
},
{
toolName: 'minireset'
},
{
toolName: 'jgthms'
}
]
},
computed: {
style: function () {
var toolsList = this.tools;
var toolNameStyle = '';
for (var i = 0; i < toolsList.length; i++) {
toolNameStyle = 'icon--' + toolsList[i].toolName;
console.log('toolNameStyle: ' + toolNameStyle);
return toolNameStyle;
}
}
}
})