How to specify multiple dynamic attributes by single computed prop in VueJS

Viewed 2783

I have this html element:

<a href="javascript:">Link text</a>

I want to add data-tooltip and title attributes dynamically by condition:

<a href="javascript:" data-toggle="tooltip" title="Some tooltip text">Link text</a>

Is there any way in VueJS to add multiple dynamic attributes at same time:

<!-- instead of this: -->
<a href="javascript:" :data-toggle="computedPropTooltipToggle" :title="computedPropTooltipTitle">Link text</a>

<!-- something like this: -->
<a href="javascript:" ...tooltipAttributes >Link text</a>
3 Answers

You could take advantage of v-bind on the DOM element you wish to apply multiple attributes to based on some dynamically changing condition.

Here's a Plunker example demonstrating how you might go about it.

Take note of the object returned:

computed: {
  multiAttrs() {
    return this.showAttrs ? {
      'data-toggle': 'tooltip',
      title: 'Some tooltip text',
    } : null;
  }
}

You should be able to use v-bind="tooltipAttributes"

the docs here https://v2.vuejs.org/v2/api/#v-bind have more info, but the key part is under usage

Dynamically bind one or more attributes, or a component prop to an expression.

From the Docs:

1. You can dynamically bind multiple attributes/props to a single element by using v-bind:
(no colon, no extra attribute, just v-bind)

<a href="#" v-bind="tooltipAttributes" >Link text</a>

2. And then declare the variable in the computed section:
(you can also declare it in the data section, but that would require manual direct value changes)

computed() {
  return {
    tooltipAttributes: {
      title: 'Title',
      'data-toggle': this.toggle === true && !disabled
    }
  }
}

Note: Attributes with dashes/hyphens - in them (e.g. data-toggle) need to be a string because Javascript doesn't recognize - as a valid symbol in variable naming.


This is THE SAME AS:

<a href="#" title="Title" :data-toggle="this.toggle === true && !disabled" >Link text</a>
Related