Dynamic attribute names let you set HTML attributes using variable names. This helps when you want to change attribute names based on data or conditions.
0
0
Dynamic attribute names in Vue
Introduction
You want to bind different attributes to an element based on user input.
You need to toggle between attributes like 'aria-label' or 'title' dynamically.
You want to reuse a component but change which attribute it sets without rewriting code.
You want to add custom data attributes where the attribute name depends on some logic.
Syntax
Vue
<element v-bind:[attributeName]="value"></element>The square brackets [] around attributeName tell Vue to treat it as a variable.
The value can be any JavaScript expression or variable.
Examples
Here, the attribute name is stored in
attrName. It will set that attribute with the value of buttonText.Vue
<button v-bind:[attrName]="buttonText">Click me</button>This input element gets an attribute name from
dynamicAttr and sets its value to inputValue.Vue
<input v-bind:[dynamicAttr]="inputValue" />You can use template literals to create attribute names dynamically, like
data-type.Vue
<div v-bind:[`data-${type}`]="info"></div>
Sample Program
This Vue component binds the title attribute dynamically to the input element. The attribute name is stored in attrName. The input's title attribute will show a tooltip with 'Hello Vue!' when hovered.
Vue
<template>
<div>
<input v-bind:[attrName]="inputValue" placeholder="Type something" />
<p>Attribute name: {{ attrName }}</p>
<p>Input value: {{ inputValue }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const attrName = ref('title')
const inputValue = ref('Hello Vue!')
</script>OutputSuccess
Important Notes
Dynamic attribute names only work with v-bind and require square brackets.
Make sure the attribute name is a valid HTML attribute or custom attribute.
Use this feature to keep your templates flexible and reusable.
Summary
Dynamic attribute names let you set attribute names using variables.
Use v-bind:[variable] syntax to bind dynamically.
This helps make components flexible and adapt to different needs.