0
0
Vueframework~30 mins

Dynamic attribute names in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Attribute Names in Vue
📖 Scenario: You are building a simple Vue 3 component that displays a button. The button's attribute name changes dynamically based on a variable. This is useful when you want to toggle attributes like disabled, aria-pressed, or others depending on the app state.
🎯 Goal: Create a Vue 3 component that uses a dynamic attribute name bound to a variable. The attribute should be set to true on the button element.
📋 What You'll Learn
Create a reactive variable called attrName with the value 'aria-pressed'.
Create a reactive variable called attrValue with the value true.
Use Vue's : [ ] binding syntax to bind the attribute named by attrName to the value in attrValue on a <button> element.
The button should display the text Toggle.
💡 Why This Matters
🌍 Real World
Dynamic attribute binding is useful in real apps to toggle accessibility attributes or states like 'disabled', 'aria-pressed', or custom data attributes based on user interaction or app state.
💼 Career
Understanding dynamic bindings in Vue is important for frontend developers to build flexible, accessible, and interactive user interfaces.
Progress0 / 4 steps
1
Setup Vue component with reactive attribute name
Create a Vue 3 component using <script setup>. Inside it, create a reactive variable called attrName and set it to the string 'aria-pressed'.
Vue
Need a hint?

Use ref from Vue to create a reactive variable named attrName.

2
Add reactive attribute value
Inside the same <script setup>, create another reactive variable called attrValue and set it to the boolean true.
Vue
Need a hint?

Use ref again to create attrValue with the boolean true.

3
Bind dynamic attribute to button
In the <template>, add a <button> element. Use Vue's dynamic binding syntax with square brackets to bind the attribute named by attrName to the value in attrValue. The button text should be Toggle.
Vue
Need a hint?

Use v-bind:[attrName]="attrValue" to bind the dynamic attribute on the button.

4
Complete component with accessibility and responsiveness
Add a type attribute with value button to the <button> element for accessibility. Also, add a simple style block below the template that sets the button's font size to 1.2rem and padding to 0.5rem 1rem.
Vue
Need a hint?

Remember to add type="button" for accessibility and style the button with CSS inside a <style> block.