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://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>
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments