1

Given the following snippets of HTML, CSS, and Vue code I would like to be able to construct a series of CSS style classes dynamically using a computed property in Vue 2 and bind them to the span that already has a class of panel-icon. As seen in the CSS snippet, the class name should be in the form of .icon--toolname where toolname is grabbed from the toolName property in the JSON. When I try to save the results of the for loop to a variable and return that variable I get only one result, instead of the four that I am expecting. The overall idea is that the CSS icon-- class should match the tool name that is being displayed via 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;
            }
        }
    }
})
2
  • First of all, post an minimal example. This has nothing to do with Vue, you're returning toolsList[0] every time in style function. The execution will stop when you return a value. Commented May 28, 2018 at 17:29
  • There are many good examples for this case in the official documentation vuejs.org/v2/guide/class-and-style.html Commented May 28, 2018 at 17:39

1 Answer 1

1

No need of computed property, simply do:

<span :class="'panel-icon icon--' + tool.toolName">

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked for me. For some reason, I thought it was not possible to call tool.toolName inside the :class binding. I think I did try it, initially, but had the syntax wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.