Consider this Vue 3 component using the Composition API. What attribute will the rendered <input> element have?
<template> <input v-bind:[dynamicAttr]="inputValue" /> </template> <script setup> import { ref } from 'vue' const dynamicAttr = 'placeholder' const inputValue = ref('Enter your name') </script>
Look at how the attribute name is set using square brackets inside the binding.
The syntax v-bind:[dynamicAttr] means Vue will use the value of the variable dynamicAttr as the attribute name. Since dynamicAttr is 'placeholder', the input will have a placeholder attribute with the value from inputValue.
Which of the following Vue template bindings correctly sets a dynamic attribute name stored in attrName with value attrValue?
Remember that dynamic attribute names require square brackets inside the binding directive.
Option D uses v-bind:[attrName] which is the correct syntax for dynamic attribute names in Vue. Option D is also valid shorthand syntax for dynamic attribute names. Option D and C bind literally to an attribute named 'attrName'.
Given this Vue 3 component snippet, why does the dynamic attribute not appear on the <button> element?
<template> <button :[attr]="true">Click me</button> </template> <script setup> const attr = null </script>
Check the value of the variable used for the attribute name.
Vue uses the value of attr as the attribute name. Since attr is null, Vue cannot create an attribute with a null name, so no attribute is rendered.
In this Vue 3 component, clicking the button toggles the dynamic attribute name. What attribute does the button have after the first click?
<template> <button :[attrName]="true" @click="toggle">Toggle</button> </template> <script setup> import { ref } from 'vue' const attrName = ref('disabled') function toggle() { attrName.value = attrName.value === 'disabled' ? 'aria-pressed' : 'disabled' } </script>
Think about how the attribute name changes after the click.
Initially, attrName is 'disabled'. After the first click, it changes to 'aria-pressed'. The button then has aria-pressed="true" and no longer has the disabled attribute.
Which of the following best explains a practical reason to use dynamic attribute names in Vue?
Think about why you might want to change attribute names dynamically instead of hardcoding them.
Dynamic attribute names let you reuse the same binding logic to set different attributes depending on conditions, making components more flexible and reducing repeated code.