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.
Very so elegant solution:
<span
:data-toggle="!!col.col_spec.tooltip ? 'tooltip' : false"
:title="col.col_spec.tooltip"
>
{{ col.col_spec.title }}
</span>
Yes, yes, yes, it's just necessary that there is not an empty string, but a Boolean false
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);
}
}
A bit late, but here is my take on it:
HTML:
<span
:data-toggle="tooltip"
:data-original-title="tooltipTitle"
>
{{ tooltipTitle }}
</span>
Vue:
methods: {
tooltipTitle: function() {
var title = this.col.col_spec.title;
if (!!title) return title;
return false;
}
}
This will remove the "data-original-title" attribute if there is none to display, consequently removing the tooltip altogether. You must use "data-original-title" instead of just "title" because Bootstrap will automatically add it once you initialise the "title" attribute, and changing "title" to false will not remove the "data-original-title".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With