1

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>
2
  • 1
    Do you mean something like this :download = "downloadable && 'filename' || null"? Commented Aug 16, 2018 at 10:27
  • No, that's the thing, download is an HTML attribute and it only cares if it's present. I want to avoid rendering download in the final HTML base on the prop downloadable Commented Aug 16, 2018 at 10:28

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

3 Comments

The attribute download is not a boolean, it's a string
Yes, and that's why you can't add this attribute in Vue way
You need javascript for that. And that's what is explained in my answer. Other than boolean attribute, you can't add or remove it using vue
1

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.

1 Comment

It seems a little bit hacky but I don't there are much options beside using the DOM. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.