Vue : v-on directive

Vue : v-on directive

Syntax

Vue provides a very nice way to integrate event listeners on any element of the DOM. As with other methods, event callback methods have direct access to Vue data using this keyword.

a) Standard syntax

To attach an event listener to any HTML element, we use the v-on directive: to which we name the event type we are listening for. In addition, at the end of such syntax, we need to “assign” the appropriate event handler method.

<button v-on:click="someEventHandler"></button>
<script>
    let vm = new Vue ({
        methods: {
            someEventHandler : function (event) {
                console.log(event.target)
            }
        }
    });
</script>

Short syntax writing

<button @click="someEventHandler"></button>

b) Object syntax for multiple “hooked” events

This syntax is used when we “attach” multiple events to the same element

<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

Passing arguments to a handler function:

a) Forwarding only the event object

If no argument is passed within the directive, Vue.js automatically in the background always passes the “event object”. Therefore, we can always use it and invoke it as part of the event handler method.

Example

HTML

<div id="app">
	<h4>Forwarding an Event object</h4>
	<input type="text" v-on:input="changeMessage"  placeholder="Please enter your name">
	<p>Your name  {{ message }} have {{ brSlova }} letters</p>
	<p>Time stamp of events {{vrijeme}} </p>
</div>

SCSS

#app{
	padding:2rem;
}

Babel

let app = new Vue ({
	el: "#app",
	data: {
		message : "",
		vrijeme: ""
	},
	methods: {
		changeMessage: function (event){
			this.message=event.target.value;
			this.brSlova=this.message.length
			this.vrijeme=event.timeStamp;
		}
	}
});

b) passing the argument

When we want to pass a parameter to a callback function that is not an event object, we need to use the following syntax:

<button v-on:click="someEventHandler('specificniArgument')"></button>

Example

HTML

<div id="app">
	<h4>Passing the argument</h4>
	<button class="btn-primary btn" v-on:click="povecaj('Increase')">Increase the counter</button>
	<button class="btn-danger btn" v-on:click="smanji('Decrease')">Decrease the counter</button>
	<p id="ispis" >{{ brKlikova }} {{ message }}</p>
</div>

SCSS

#app{
	padding:2rem;
}

Babel

let app = new Vue ({
	el: "#app",
	data: {
		message:"",
		brKlikova: 0,
		brSlova: 0
	},
	methods: {
		povecaj: function (prosledjeno){
			this.brKlikova++;
			this.message=prosledjeno;
		},
		smanji: function (prosledjeno){
			this.brKlikova--;
			this.message=prosledjeno;
		}
	}
});

c) Passing the argument and event object

In addition to a specific parameter, when we want to pass a callback function to an “event object” we need to specify it with “$event“:

<button v-on:click="someEventHandler('specificniArgument', $event)"></button>

Event modifiers

Modifiers of a directive are special postfixes that build on the use of a point on a directive, and by their existence indicate that the directive needs to be modified in some special way.

REMARK:
Event modifiers can be stacked <button @click.stop.prevent=”doThis”></button>
Because they are executed in the order they are listed, care should be taken.

.stop

When this modifier overrides a directive, it has the same functionality as if we called the event.stopPropagation () method as part of the event handler to prevent event propagation

Example

HTML

<div id="app">
	<p>The mouse coordinates are: x: {{ x }} - y: {{ y }}</p>
	<div id="povrs" v-on:mousemove="updateCoordiates">
		<div id="neaktivna" v-on:mousemove.stop=""><p>No event propagates on this surface, so the event listener on the parent element does not register it</p></div>
	</div>
</div>

SCSS

#app {
	padding:0.5;
	p {
		color:black;
		text-align: center;
	}
	#povrs {
		margin: 0 auto;
		width:400px;
		height:150px;
		background-color:#563dcc;
	}
	#neaktivna{
		width:300px;
		height:100px; 
		background-color:red;
		margin-left:50px;
		p {
		color:white;
		}
	}
}

Babel

let vm = new Vue ({
	el: "#app",
	data : {
		x: 0,
		y: 0
	},
	methods : {
		updateCoordiates : function (event){
				this.x = event.clientX,
				this.y = event.clientY
		}
	}
})

.prevent

When this modifier overrides the directive, it has the same functionality as if we called the event.preventDefault () method as part of the event handler.

<!-- just the modifier -->
<form v-on:submit.prevent></form>

Example

In this example, using the .prevent modifier, we prevent the default behavior of the form from clicking on the “calculate” button to submit. If this code did not use the “prevent” modifier then it would reload immediately after clicking the page button because we are submitting the form. Clicking on the button would also invoke the event handler “calculate”, but the page would reload and not see the result. It should be clarified that they would achieve the same functionality without a modifier by inserting the event.preventDefault () code; at the beginning of the calculation method. However, using the modifier is simpler and the very look at HTML makes it clear that the default behavior of the form is prevented.

HTML

<div class="app">
	<h2>.prevent modifier</h2>
	<br>
   <h5>Enter two numbers and an operation</h5>
    <form class="form-inline">
        <input v-model.number="a" class="form-control">
        <select v-model="operator" class="form-control">
             <option>+</option>
             <option>-</option>
             <option>*</option>
             <option>/</option>
          </select>
        <input v-model.number="b" class="form-control">
        <button type="submit" v-on:click.prevent="calculate" class="btn btn-primary">Calculate</button>
   </form>
   <h5>Result: {{a}}  {{operator}}  {{b}} = {{c}}</h5>
	<br><br>
</div>

SCSS

@media (max-width: 768px){
	.form-inline .form-control {
    display: inline-block;
    width: 60px;
    vertical-align: middle;
 	}
}
.app{
	padding: 2rem;
}

Babel

new Vue({
  el: '.app',
  data: {
    a: 1,
    b: 2,
    c: null,
    operator: "+",
  },
  methods:{
      calculate: function(){
        switch (this.operator) {
          case "+":
              this.c = this.a + this.b
              break;
          case "-":
              this.c = this.a - this.b
              break;
          case "*":
              this.c = this.a * this.b
              break;
          case "/":
              this.c = this.a / this.b
              break;
        }
      }
  },
});

Key modifiers

These modifiers allow the event handler function to be activated only if a specific button is used. The most commonly used key modifiers are:

  • .enter
  • .tab
  • .A portion
  • .esc
  • .Space
  • .up
  • .down
  • .left
  • .right
  • In addition to these “ordinary” keyboard buttons, system buttons are also commonly used:
  • .ctrl
  • .alt
  • .shift
  • .meta (on macintosh ⌘ and on windows ⊞)

Example

<input @keyup.alt.67="clear">  // Alt + C
 
<div @click.ctrl="doSomething">Do something</div> // Ctrl + Click

Example

In addition to the name of the button, we can also use their alias (Enter is 13):

<input v-model="b" @keyup.enter="calculate">
<input v-model="a" @keyup.13="calculate">

Mouse modifiers

These modifiers are used to more clearly define an event related to mouse operation, depending on the button used.

  1. .left
  2. .right
  3. .middle

The left button is the default onclick event, while the right button is the default oncontextmenu, the middle button does not have a default event type. In addition to the default events, all three buttons can also be used onmousedown or onmouseup events. Since there is no need to use modifiers for the default events, it follows that we use mouse modifiers only for “onmousedown” or “onmouseup” events.

Likes:
15 0
Views:
1920
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *