Vuejs Course


Listening for Events

VueJS uses the v-on attribute added in HTML tags to listen to the events.
Usually, the value of the v-on attribute is the name of a method defined in the methods property. The specified method is called when the event is emitted.

Basic syntax:
<button v-on:eventName='methodName'>Try it</button>

<script>
var vm = new Vue({
 //...
 methods:{
 methodName: function(event){
 //code to execute..
 }
 }
})
</script>
- eventName is the name of the event: click, input, mouseenter, etc.

Simple example with the click event:
<div id='demo'>
<h1>{{hi}}</h1>
<button v-on:click='greet'>Try it</button>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {hi: ''},
 methods:{
 greet: function(ev){
 this.hi ='Hello brother';
 }
 }
})
</script>

You can set the event handler from v-on to pass a value, and the event instance to the method:
<button v-on:eventName='methodName("string", $event)'>Try it</button>

<script>
var vm = new Vue({
 //...
 methods:{
 methodName: function(value, event){
 //code to execute..
 }
 }
})
</script>

Test and study the following example:
<div id='demo'>
<h1>{{hi}}</h1>
<a href='/' v-on:click='test("The link not works", $event)'>Open the page</a>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {hi: ''},
 methods:{
 test: function(val, ev){
 this.hi = val;
 if(ev){
 ev.preventDefault();
 alert('Link address: '+ ev.target.href);
 }
 }
 }
})
</script>

Multiple events in v-on

You can add multiple events into an object in a single v-on directive, but without an argument.
- Syntax:
<button v-on={event_1:method_1, event_2:method_2}>Try it</button>

Note: With this method you cannot add modifier, nor pass an argument to the event handler, but it is automatically passed the event instance object.


Example:
<div id='demo'>
<div v-bind:style='styleobj' v-on='{mouseenter:bground, mouseleave:bground}'>Place the mouse here</div>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 styleobj:{background:'#fbfc00', height:'111px', width:'111px'}
 },
 methods:{
 bground: function(ev){
 let bgr ={mouseenter:'#bbbbfe', mouseleave:'#00e000'};
 this.styleobj.background = bgr[ev.type];
 }
 }
})
</script>

Event Modifiers

Vue has event modifiers available on v-on attribute. They are directive postfixes denoted by a dot.
Syntax:
<button v-on:eventName.modifier='methodName'>Try it</button>

Examples with some modifiers available in Vue:
prevent - calls event.preventDefault().
 
<form action='/' id='frm1' v-on:submit.prevent='test'>
The submit event will not reload the page, but will call a Vue method.<br>
<input type='text' name='inp1' value='MarPlo'/> <input type='submit' value='Send'/>
<div>{{text}}</div>
</form>

<script>
var vue_ob = new Vue({
 el: '#frm1',
 data: {
 text:''
 },
 methods:{
 test: function(ev){
 this.text = ev.target.inp1.value;
 }
 }
})
</script>
once - trigger handler at most once.
<div id='demo'>
Nr. clicks: <b>{{nrc}}</b><br>
Only one click is emitted: <button v-on:click.once='nrc +=1'>Click</button>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 nrc:0
 }
})
</script>
self - only trigger handler if event was dispatched from this element, not from a child element.
<div id='demo'>
Click event is registered with '<b>self</b>' modifier on Parent.<br>
If you click on the Child element, it will have no effect.<br>
Nr. clicks: <b>{{nrc}}</b><br>
<div style='background:#b0b0fe; height:144px; text-align:center; width:220px' v-on:click.self='nrc +=1'>
Parent
<div style='background:#00da00; margin:12px; height:88px; width:115px'>Child</div>
</div>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 nrc:0
 }
})
</script>
left | middle | right - only trigger handler for left, middle or right button mouse events.
<div id='demo'>
It registers the clicks on the right button mouse: <b>v-on:click.right.prevent</b>.<br>
The <b>prevent</b> modifier is added to stop default behavior (here to stop opening menu on right click).<br><br>
Nr. clicks: <b>{{nrc}}</b><br>
<div style='background:#afaffe; height:144px; text-align:center; width:222px' v-on:click.right.prevent='nrc +=1'>
Right click here
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 nrc:0
 }
})
</script>

You can chain multiple modifiers on an event with v-on, see in the example above: v-on:click.right.prevent.


Key Modifier

Vue.js allows adding key modifiers to v-on when listening for key events.
- Syntax:
v-on.eventname.keyname
We can make use of multiple keynames. For example: v-on.onkeydown.ctrl.enter

- Example:
<div id='demo'>
Add some text, then press enter.
<form action='/' v-on:keydown.enter.prevent='submitFrm'>
<input type='text' value='MarPlo'/>
<div v-html='str'></div>
</form>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 str:''
 },
 methods:{
 submitFrm:function(ev){
 this.str ='The form submits the text: <b>'+ ev.target.value +'</b>';
 }
 }
})
</script>

v-on.event shorthand

You can replace the v-on: with the character @ in Vue syntax, as a shorthand for v-on:.
- Syntax:
<div @eventName='methodName'></div>

Dynamic events

You can also use Dynamic events, which are added between square brackets:
v-on:[event]='methodName'

//OR
@[event]='methodName'

Example:
<div id='demo'>
<h1>{{hi}}</h1>
<button @[ev_name]='greet'>Try it</button>
</div>

<script>
var vue_ob = new Vue({
 el: '#demo',
 data: {
 hi: '',
 ev_name: 'click'
 },
 methods:{
 greet: function(ev){
 this.hi ='Forgive the past, love the present, trust the future.';
 }
 }
})
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Vue JS - Events

Last accessed pages

  1. Break and Continue (2356)
  2. Uploading images to server with Ajax (6100)
  3. Convert BBCode to HTML and HTML to BBCode with JavaScript (9436)
  4. Get Mime Type of file or string content in PHP (6270)
  5. MD5 hash string in JavaScript (4831)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (511)
  2. CSS cursor property - Custom Cursors (67)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (48)
  4. The Mastery of Love (47)
  5. Read Excel file data in PHP - PhpExcelReader (43)