César Alberca
César Alberca

Reputation: 2681

How can I add dynamically an attribute with VueJS?

I know I can set a value to an attribute dynamically with v-bind, however I would like add dynamically the attribute, not the value. Something like this (although this is not valid):

    <a
      :href="url"
      {{ downloadable ? 'download' : null }}
      class="link"
      @click="onClick">
      {{ text }}
    </a>

Note: I'm not using JSX

I was thinking about using $attrs (https://v2.vuejs.org/v2/api/#vm-attrs) but it's read only.

Is there a way to do this on Vue?

Solution:

JavaScript:

new Vue({
  el: '#app',
  data() {
    return {
       msg: 'Inspect element to test',
       downloadable: true
    }
  },
  computed: {
    dynamicAttribute() {
      if(!this.downloadable) {
         return null
      }

      return { [`download`]: "link or w/e" }
    }
  }
})

HTML:

  <a v-bind="dynamicAttribute">{{msg}}</a>

Upvotes: 1

Views: 1935

Answers (2)

dziraf
dziraf

Reputation: 3653

If you want it to look like:

<a ... download="value">text</a>

with download visible only when downloadable is true, you can actually do it using v-bind:

https://jsfiddle.net/eywraw8t/274691/

You can check if it works by changing downloadable to true or false and inspecting the element.

Upvotes: 1

santanu bera
santanu bera

Reputation: 1311

Other than boolean attribute you cannot dynamically add or set attribute using Vue.js. For example -

v-bind:disabled="isActive"

If isActive is true, then the attribute disabled will be added to the element, otherwise it will be removed. This mechanism doesn't work for other attribute which are not boolean.

You can use Javascript for that purpose -

element.setAttribute('attributeName', 'value');

Upvotes: 2

Related Questions