Understanding Event Binding on VueJs
In this blog, we are going to learn Event Binding on VueJs. Vue gives us an easier way of adding EventListeners to HTML elements.
When DOM events occur, we can use the v-on directive, which we usually shorten with the @ symbol, to listen for them and execute some JavaScript.
Ex:
v-on:click="handler"
One of the following values can represent the handler:
1. Inline handler
2. Method handler
1. Inline handler
The inline handler executes when the event is triggered
Ex:
inline(){ return { count:0 } } <button @click=”count++”>add 1</button> <p>Count is:{{count}}</p>
2. Method handler
A property name or path called a “method handler” points to a method that has been declared on the component.
Ex:
data():{ return :{ name:”vuejs” } } Method:{ greet1(event) { alert(`Hello ${this.name}!`) if (event) { alert(event.target.tagName) } } } <button @click="greet1">Greet</button>
Calling Methods in Inline Handlers:
methods: { say1(message) { alert(message) } } <button @click="say1('hello')">Say hello</button>
Event Modifiers:
.stop: the click event’s propagation will be stopped
.prevent: just the modifier
.self: not from a child element
.capture: use capture mode when adding the event listener.
.once: At most once, the click event will be triggered.
.passive: the scroll event’s default behavior (scrolling) will happen
Key Modifiers:
You may tell a function which key event to execute by using key modifiers.
Vue allows modifiers for v-on or @ for key events
<input @keyup.enter="submit" />
What is V-bind:
V-bind is helpful for setting the value of an attribute.
The v-bind directive is a Vuejs directive used to bind one or more attributes or a component prop to an element.
Ex:
v-model:title=”PageTitle”