Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js conditional rendering of an attribute [duplicate]

Tags:

vue.js

vuejs2

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.

like image 730
pilat Avatar asked Jan 16 '17 17:01

pilat


3 Answers

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

like image 65
arkadij_ok Avatar answered Nov 14 '22 11:11

arkadij_ok


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);
    }
}
like image 32
Bert Avatar answered Nov 14 '22 11:11

Bert


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".

like image 3
nikojpapa Avatar answered Nov 14 '22 10:11

nikojpapa