CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Example of Vue Event handling in a component

Use v-on to listen for events.

window.onload = function() { Vue.component('text-input', { template: `<div> <button v-on:click='counter += 1'>Add 1</button> <p>The button has been clicked {{ counter }} times.</p> </div>`, data: function() { return { counter: 0 }; } }); var app = new Vue({ el: '#demo' }); }
DO IT

In this example, let's turn it into a function. Change counter += 1 to:

increment( 5 )

And add a method call increment:

window.onload = function() { Vue.component('text-input', { template: `<div> <button v-on:click='increment(5)'>Add 5</button> <p>The button has been clicked {{ counter }} times.</p> </div>`, data: function() { return { counter: 0 }; }, methods: { increment: function( inc ) { this.counter += inc; } } }); var app = new Vue({ el: '#demo' }); }
DO IT

And now we're going to pass the event object, so we can access it:

window.onload = function() { Vue.component('text-input', { template: `<div> <button v-on:click='increment(5, $event)'>Add 5</button> <p>The button has been clicked {{ counter }} times.</p> <p>{{ theTag }}</p> </div>`, data: function() { return { counter: 0, theTag: '' }; }, methods: { increment: function( inc, event ) { this.counter += inc; this.theTag = event.target.tagName; } } }); var app = new Vue({ el: '#demo' }); }
DO IT

The abbreviation @:click is the same thing as v-on:click


Keystrokes

You can set event handlers based on the key stroke. v-on:keyup.13= specifies the function to call when the user presses enter. Once the user presses enter, setVal will be called.

Go ahead an add the following code. Hit run, then type into the input box and then press enter.

window.onload = function() { Vue.component('text-input', { template: `<div> <input type='text' v-model='val' v-on:keyup.13='setVal'></input> <p>{{ val }}</p> </div>`, data: function() { return { val: '' }; }, methods: { setVal: function() { this.val = ''; } } }); var app = new Vue({ el: '#demo' }); }
DO IT

Since numbers are hard to remember Vue provides aliases that are easier to remember. So v-on:keyup.13 becomes v-on:keyup.enter, etc.

Substitute 13 for other keystrokes: enter, tab, delete, esc, space and left.

In the next lesson, we will learn about Example of Computed properties vs watched properties

Get the Latest Tutorial Updates
<< >>
X