ref to access a DOM element. What will be logged when the button is clicked?<template> <input ref="inputRef" /> <button @click="logInputValue">Log Value</button> </template> <script setup> import { ref } from 'vue' const inputRef = ref(null) function logInputValue() { console.log(inputRef.value.value) } </script>
inputRef.value points to the DOM element, and .value on that element is the input's text.In Vue 3, ref creates a reactive reference. When used with ref="inputRef" on an input element, inputRef.value points to the actual DOM input element. Accessing inputRef.value.value gets the current text inside the input box.
<script setup>?ref(null) to work properly.Option C correctly imports ref from Vue and initializes textAreaRef with ref(null). This allows Vue to assign the DOM element to textAreaRef.value. Other options either don't initialize properly or use wrong APIs.
<template> <input ref="myInput" /> <button @click="focusInput">Focus</button> </template> <script setup> import { ref } from 'vue' const myInput = ref(null) function focusInput() { myInput.focus() } </script>
value property holding the actual DOM element.myInput is a ref object. To access the DOM element, you must use myInput.value. Calling myInput.focus() tries to call focus on the ref object itself, which causes an error.
inputRef.value.value after mounting this Vue 3 component?console.log(inputRef.value.value) output right after the component is mounted?<template> <input ref="inputRef" value="Hello Vue" /> </template> <script setup> import { ref, onMounted } from 'vue' const inputRef = ref(null) onMounted(() => { console.log(inputRef.value.value) }) </script>
value attribute sets the initial text inside the input element.When the component mounts, inputRef.value points to the input DOM element. The value property of that element contains the initial text "Hello Vue".
Template refs give direct access to DOM elements but do not create reactive data bindings. Changes to DOM properties accessed via refs do not trigger Vue's reactivity system, so they should not be used to manage reactive state.