Search code examples
vue.js

vue templating in a slot with v-if


The original code I have is

       <slot v-for="result in data.results" :key="result">
        <span v-if="result.success" class="status status-success rounded bg-success" @mouseenter="showTooltip(result, $event)" @mouseleave="showTooltip(null, $event)"></span>
        <span v-else class="status status-failure rounded bg-red-600" @mouseenter="showTooltip(result, $event)" @mouseleave="showTooltip(null, $event)"></span>
       </slot>

I can have a <span>{{ result.color }}</span> statement inside that gets expanded as expected. However what I want is:

<span v-if="result.color" class="status color-{{ result.color }} rounded bg-success" @mouseenter="showTooltip(result, $event)" @mouseleave="showTooltip(null, $event)"></span>

The double mustache syntax does not get expanded instead i get verbatim color-{{ result.color }}. How do I template inside the class attribute?

Unfortunately my vue knowledge is non-existent to fresh.

(for context this is the code I want to tune for my needs: https://github.com/TwiN/gatus/blob/v5.12.1/web/app/src/components/Endpoint.vue#L30)


Solution

  • {{ }} can be used only in text nodes (not in attributes like you try), just use a string template literal:

    :class="`status color-${ result.color } rounded bg-success`"