How can I react to focusing / unfocusing of elements in vue?
- User
How can I react to focusing / unfocusing of elements in vue?
- Assistant
How can I react to focusing / unfocusing of elements in vue?
In Vue.js, you can react to focusing and unfocusing (blurring) of elements by using event listeners. Specifically, you'll use the @focus and @blur event directives on your elements. Here’s how you can do it:
Define Your Methods: In your Vue component, define the methods that will handle the focus and blur events.
<template>
<div>
<input
@focus="handleFocus"
@blur="handleBlur"
type="text"
placeholder="Focus on me!"
/>
</div>
</template>
<script>
export default {
methods: {
handleFocus(event) {
console.log('Element focused:', event.target);
// Additional logic for when the element is focused
},
handleBlur(event) {
console.log('Element blurred:', event.target);
// Additional logic for when the element loses focus
}
}
}
</script>
<style scoped>
/* Add any styles here */
</style>
Using Data Properties: If you need to toggle a class or manage some data property when the element is focused or blurred, you can set a data property and update it within your methods.
<template>
<div>
<input
@focus="isFocused = true"
@blur="isFocused = false"
type="text"
placeholder="Focus on me!"
:class="{ focused: isFocused }"
/>
</div>
</template>
<script>
export default {
data() {
return {
isFocused: false
};
}
}
</script>
<style scoped>
.focused {
border-color: blue;
}
</style>
Although focus and blur events are best handled with methods directly, you may sometimes want to monitor changes using computed properties or watchers, especially if the state impacts other components or requires more complex reactivity.
<template>
<div>
<input
@focus="isFocused = true"
@blur="isFocused = false"
type="text"
placeholder="Focus on me!"
:class="{ focused: isFocused }"
/>
</div>
</template>
<script>
export default {
data() {
return {
isFocused: false
};
},
watch: {
isFocused(newValue) {
if (newValue) {
console.log('Element is focused');
// Additional logic when focused
} else {
console.log('Element is blurred');
// Additional logic when blurred
}
}
}
}
</script>
<style scoped>
.focused {
border-color: blue;
}
</style>
Using Vue's event system, you can handle focus and blur events effortlessly with the @focus and @blur directives. This allows you to run custom logic, toggle classes, or update other data properties whenever an element gains or loses focus.
Not yet included in a published release.