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 elementAdd a button that triggers a function to change the paragraph's text color
Use the
ref function from Vue to create the template refModify 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