0
0
Vueframework~30 mins

Template refs for DOM access in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Template refs for DOM access
📖 Scenario: You are building a simple Vue 3 app where you want to access a DOM element directly to change its style when a button is clicked. This is useful when you want to interact with the page elements without using data binding.
🎯 Goal: Create a Vue 3 component that uses a template ref to access a paragraph element and change its text color to blue when a button is clicked.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a template ref named textRef to access the paragraph element
Add a button that triggers a function to change the paragraph's text color
Use the ref function from Vue to create the template ref
Modify the paragraph's style directly using the template ref
💡 Why This Matters
🌍 Real World
Direct DOM access with template refs is useful when you need to manipulate elements that are not easily handled by reactive data, such as focusing inputs, measuring sizes, or applying styles dynamically.
💼 Career
Understanding template refs is important for Vue developers to handle edge cases and improve user experience by controlling DOM elements directly when needed.
Progress0 / 4 steps
1
Create the paragraph element with a template ref
Write the Vue 3 template code to create a paragraph element with the text "Hello, Vue!" and add a template ref named textRef to it.
Vue
Need a hint?

Use ref="textRef" inside the paragraph tag to create the template ref.

2
Create the template ref variable in script setup
In the <script setup> block, import ref from 'vue' and create a template ref variable named textRef initialized to null.
Vue
Need a hint?

Use import { ref } from 'vue' and then const textRef = ref(null).

3
Add a button and a function to change text color
Add a button with the text "Change Color" inside the template. In the <script setup> block, create a function named changeColor that sets the paragraph's style color to 'blue' using the textRef template ref. Bind the button's click event to the changeColor function.
Vue
Need a hint?

Define changeColor function and use textRef.value.style.color = 'blue'. Add a button with @click="changeColor".

4
Add accessibility and responsive styling
Add an aria-label attribute with value "Change text color" to the button for accessibility. Also, add a simple responsive style inside a <style scoped> block that sets the paragraph font size to 1.5rem on screens wider than 600px.
Vue
Need a hint?

Add aria-label="Change text color" to the button. Use a media query @media (min-width: 600px) to set p font size to 1.5rem.