Your browser does not support JavaScript!
Upvotes Anonymous 18 User 0

Introduction to VueJS Events

VueJS makes working with forms really easy. Let's create some interactions with an input box and a button, with the end result looking like this:
When we click the Submit button, or press the Enter key in the input box, we see two alerts. One alert has the text we entered:
and the other has the button HTML:
The Form HTML
VueJS does not depend on jQuery, but I've included it to create a document ready() handler (to create our Vue instance after the document is ready).
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>VueJS Button Click</title>
  <script src="js/jquery-2.1.4.min.js"></script>
  <script src="js/vue.js"></script>
  <script src="js/index.js"></script>

  <div id="my-container">
    <input type="text" v-model="firstName" @keyup.enter="onSubmit"/>
    <button @click="onSubmit">Submit</button>


Let's explain what we're doing in the HTML above. We first create a container:
<div id="my-container"></div>
We create a container because Vue wires up our methods (events) and data in relation to the container (it traverses the DOM inside the container, when we create a new instance).

Then we create an <input> box:
<input type="text" v-model="firstName" @keyup.enter="onSubmit"/>

We use v-model="firstName" (a directive) to indicate that we'll be getting and setting the input element's value.

We also wire up an event using key modifiers (@keyup.enter="onSubmit"). After the Enter key is pressed, our onSubmit method is called.

The @ is shorthand for v-on: (shorthands).
The JavaScript (index.js)
Below we define an onSubmit method that has access to the firstName property, as well as the event object (method handlers and properties). Vue conveniently sets this so that it refers to the Vue instance.
$(document).on('ready', function () {

    new Vue({
        el: '#my-container',
        methods: {
            onSubmit: function (evt) {
                alert(this.firstName); //alerts whatever you put in the input box
                alert(; //alerts the HTML inside the button you clicked
        data: {
            firstName: ''

The Code
You can download the code below:
Was this helpful?


Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License