Vue add event listener to ref:In Vue, a ref
is a way to get a reference to an element or component in the template. To add an event listener to a ref
, you first need to assign the ref
to a variable in the component’s script section using the ref
attribute.
Once you have a reference to the element or component, you can use the addEventListener
method to attach an event listener to it. You can do this in the mounted
lifecycle hook, which is called when the component is inserted into the DOM.
How can I add an event listener to a Vue js ref element?
Here’s a more detailed explanation:
- The code defines a Vue.js app using the
Vue.createApp()
method and passes in an options object with three properties:mounted()
,beforeUnmount()
, andmethods
. - The
mounted()
method is a lifecycle hook that is called when the Vue instance is mounted on the DOM. Within this method, the code usesthis.$refs
to access themyButton
element and adds an event listener for theclick
event. The event listener is bound to thehandleClick()
method, which will be called whenever the button is clicked. - The
beforeUnmount()
method is another lifecycle hook that is called before the Vue instance is unmounted. Within this method, the code usesthis.$refs
again to access themyButton
element and removes the event listener for theclick
event. This ensures that the event listener is cleaned up when the Vue instance is destroyed. - The
methods
property is an object that contains thehandleClick()
method, which is triggered when theclick
event is fired on the button element. In this case, the method simply displays an alert with the message “Button clicked”.
Overall, this code demonstrates how to add and remove event listeners for a Vue.js ref element using lifecycle hooks.
Vue add event listener to ref Example
<div id="app">
<button ref="myButton">Click me</button>
</div>
<script type="module">
const app = Vue.createApp({
mounted() {
this.$refs.myButton.addEventListener('click', this.handleClick)
},
beforeUnmount() {
this.$refs.myButton.removeEventListener('click', this.handleClick)
},
methods: {
handleClick() {
alert('Button clicked')
}
}
})
app.mount('#app')
</script>