Vue.js Template Refs
Syntax
<template>
<div>
<input type="text" #myInput>
<button @click="$refs.myInput.focus()">Focus Input</button>
</div>
</template>
Example
<template>
<div>
<input type="text" #myInput>
<button @click="$refs.myInput.focus()">Focus Input</button>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.myInput.value);
}
}
</script>
Output
The output of the above example will be a text input field with a button that focuses the input field when clicked. The Vue component also logs the value of the input field to the console on mount.
Explanation
Vue.js template refs
provide a way to reference an element in a Vue component template. This allows you to access the element's properties or methods programmatically from within the component's JavaScript code.
The syntax for adding a reference to an element is to add #refName
to the element as a directive. Then, you can access the element in the component's JavaScript code using this.$refs.refName
.
In the example above, when the button is clicked, the focus()
method is called on the myInput
element reference, which sets the focus on the input field. When the component is mounted, the value
property of the myInput
element reference is logged to the console.
Use
Vue.js template refs are useful when you need to access an element's properties or methods from the component's JavaScript code. This can be useful for things like form validation, manipulating the DOM, or creating custom controls.
Important Points
- Vue.js template refs are used to reference an element in a Vue component template.
- The syntax for adding a reference to an element is to add
#refName
to the element as a directive. - You can access the element in the component's JavaScript code using
this.$refs.refName
. - Vue.js template refs should be used sparingly and only when necessary as they can lead to tightly coupled code.
Summary
Vue.js template refs
provide a convenient way to reference an element in a Vue component and access the element's properties or methods from the component's JavaScript code. The syntax is simple, but they should be used sparingly to avoid tightly coupled code. Understanding how to use Vue.js template refs can greatly enhance your ability to create rich and dynamic Vue.js applications.