Vue.js conditional attribute mapping

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

The code I have is:

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

Although I don't really like the second line ... Even if I use a computed property here, I would prefer not to have a data-toggle attribute at all when there is no tooltip to display.

+5
source share
3 answers

Here's another working, but not very 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> 
+2
source

Sort of:

 <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); } } 
+5
source

A bit late, but here is my question:

HTML:

 <span :data-toggle="tooltip" :data-original-title="tooltipTitle" > {{ tooltipTitle }} </span> 

Vu:

 methods: { tooltipTitle: function() { var title = this.col.col_spec.title; if (!!title) return title; return false; } } 

This will remove the attribute "source-source header" if it is not displayed, therefore, completely remove the tooltip. You should use "data-original-title" instead of "title" because Bootstrap will automatically add it after initializing the "title" attribute, and changing the "title" to false will not delete the "data-original-title".

+1
source

Source: https://habr.com/ru/post/1262888/


All Articles