Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'd like to learn what is the best way to conditionally render an HTML attribute in Vue.js. For example, add data-toggle="tooltip" if there is a tooltip message for current instance.

The code I have now:

<span
  :data-toggle="!!col.col_spec.tooltip ? 'tooltip' : ''"
  :title="col.col_spec.tooltip"
>
  {{ col.col_spec.title }}
</span>

Though, I don't like the 2nd line much… Even if I use computed property here, I'd prefer not to have data-toggle attribute at all, when there is no tooltip to display.

share|improve this question
1  
If you don't want the attribute to exist at all when there is no tooltip, then I would probably not do this in the template, but rather in mounted() or something like that. – Bert Evans Jan 16 at 17:28

Something like:

<span ref="column">
  {{ col.col_spec.title }}
</span>

And in Vue:

mounted(){
    if (this.col.col_spec.tooltip){
      this.$refs.column.setAttribute("data-toggle", this.col.col_spec.tooltip);
    }
}
share|improve this answer

Here's another working but not so elegant solution:

<span v-if="!!col.col_spec.tooltip" data-toggle="tooltip" >
    {{ col.col_spec.title }}
</span>
<span v-else >
    {{ col.col_spec.title }}
</span>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.