Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    LinkedIn

    Building LinkedIn Authority: Strategies for Effective Lead Generation

    Tips

    Who is a Developer Advocate?

    Programming

    7. Уроки Node.js. Модуль Console

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Friday, December 26
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Introduction to Vue.js Event Handling
    JavaScript

    Introduction to Vue.js Event Handling

    Ho-Hang JohnBy Ho-Hang JohnJanuary 20, 2020Updated:January 21, 2020No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Introduction to Vue.js Event Handling
    Introduction to Vue.js Event Handling
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Introduction to Vue.js Event Handling
    Introduction to Vue.js Event Handling

    Listening to events is an important part of creating an interactive web app.

    In this article, we’ll look at how to listening to events in a Vue app works so that we can make our app interactive by responding to them.

    Listening to Events

    We use the v-on directive to listen to DOM events and run some JavaScript code when the indicated event is triggered.

    The most basic example would be something like the following:

    index.js:

    new Vue({
      el: "#app",
      data: {
        count: 0
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button v-on:click="count += 1">Increment</button>
          <p>{{ count }}</p>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    In the code above, we have the Vue instance with the data property with the count  property that we want to update when we click on the button in index.html.

    The Increment button has the v-on:click  directive that will increase count  by 1 when we click it.

    v-on is directive and click is the event that we want to listen to with v-on .

    Method Event Handlers

    It’s rare that we only want to run only a small piece of code when we’re handling an event.

    This is why we can attach an event listener function to run code.

    For example, we can create a function to increase count by 1 instead of putting the code straight in the template.

    new Vue({
      el: "#app",
      data: {
        count: 0
      },
      methods: {
        increment() {
          this.count += 1;
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button v-on:click="increment">Increment</button>
          <p>{{ count }}</p>
        </div>
        <script src="index.js"></script>
      </body>
    </html>
    
    In the code above, we pass in the increment method from the methods property of the Vue instance in index.js into the template.Vue will call the function once the Increment button is clicked.Methods in Inline HandlersInstead of binding the click event directly to the method name, we can also call it. To do that we just make the following change in the template:index.html:<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button v-on:click="increment()">Increment</button>
          <p>{{ count }}</p>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

     

    Calling and not calling it to do the same thing, except that we can pass in arguments to our event handler function if we call it instead of just binding it to the name.

    Read More:  Implementing Role-Based Access Control in a Node.js application

    For instance, we can call it as follows:

    index.js:

    new Vue({
      el: "#app",
      methods: {
        greet(message) {
          alert(message);
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button v-on:click="greet('hi')">Greet</button>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    In the code above, we have:

    <button v-on:click="greet('hi')">Greet</button>
    

    We passed 'hi' into the greet method that we have in our Vue instance.

    Accessing the Original DOM Element from Event Handlers

    We can use the $event object to access the DOM element that triggered the event.

    For example, we can use it to get the ID of the element that triggered the click:

    index.js

    new Vue({
      el: "#app",
      methods: {
        showAlert(id) {
          alert(`ID ${id} clicked`);
        }
      }
    });

    index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button id="alert" v-on:click="showAlert($event.target.id)">Alert</button>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

     

    In the code above, we have:

    v-on:click="showAlert($event.target.id)"

    to get the ID from the button element and then show an alert box by calling the showAlert method which calls the alert function.

    Event Modifiers

    We can add modifiers after the event name argument to do some common operations like calling event.preventDefault()  or event.stopPropagation() .

    The following event modifiers can be used with v-on . Modifiers are directive postfixes denoted by a dot:

    • .stop  – stop event propagation
    • .prevent  – call event.preventDefault()  to stop the default action of the event
    • .capture  – handle events targeting an inner element before handling events of the element that triggered the event
    • .self  – only trigger if event.target  is the element itself
    • .once  – only run the event listener once
    • .passive  – opposite of calling event.preventDefault() . That is we want to let the default action run. .prevent  and .passive  shouldn’t be used together in one element.

    For example, we can use the .prevent  modifier to call event.preventDefault()  instead of having to call the method in our event handler as follows:

    index.js:

    new Vue({
      el: "#app",
      data: {
        name: ""
      },
      methods: {
        submit() {
          alert(this.name);
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <form v-on:submit.prevent="submit">
            <label>Name</label>
            <input type="text" v-model="name" />
          </form>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    The order that they’re applied matters, so v-on:click.prevent.self is different from v-on:click.self.prevent

    Key Modifiers

    We can also add key modifiers to listen to an event where specific keys are pressed.

    Read More:  Guidelines for Building Accessible Web Applications

    Key names with multiple words should be written in kebab-case.

    For instance, we can use key modifiers with v-on as follows:

    index.js:

    new Vue({
      el: "#app",
      data: {
        name: ""
      },
      methods: {
        submit() {
          alert(this.name);
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <input type="text" v-model="name" v-on:keyup.enter="submit" />
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    Then when we press enter we’ll get an alert box with what we typed in.

    We can show an alert box when the Page Down key is pressed instead:

    index.js:

    new Vue({
      el: "#app",
      data: {
        name: ""
      },
      methods: {
        onPageDown() {
          alert(this.name);
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <input type="text" v-model="name" v-on:keyup.page-down="onPageDown" />
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    Vue provides aliases for the most commonly used key codes for legacy browser support for the following keys:

    • .enter 
    • .tab
    • .delete  (captures both “Delete” and “Backspace” keys)
    • .esc
    • .space
    • .up
    • .down
    • .left 
    • .right 

    If our app need to support IE9 then we should use the aliases since IE9’s key codes are different from other browsers for keys like .esc and all arrow keys.

    System Modifier Keys

    Since Vue 2.1.0, it can also listen to key combinations that with the following system modifier keys:

    • .ctrl 
    • .alt 
    • .shift 
    • .meta 

    The meta key is the command key on a Mac keyboard and Windows key on a Windows keyboard.

    For example, we can use them as follows:
    index.js:

    new Vue({
      el: "#app",
    
      methods: {
        onCtrClick() {
          alert("Ctrl+Clicked");
        }
      }
    });

    index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <button v-on:click.ctrl="onCtrClick">Ctrl+Click Me</button>
        </div>
        <script src="index.js"></script>
      </body>
    </html>

    Then when we Ctrl+Click on the button, we see Ctrl+Clicked displayed in the alert box since onCtrlClick is called.

    Conclusion

    We can listen to events with the v-on directive. It takes various modifiers like click to listen to click events, keyup to listen to events when a key is released, etc.

    We can also use it to listen to various key combination presses like v-on:click.ctrl to listen to Ctrl + Click combinations.

    Event Handling JavaScript js vue vue.js
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ho-Hang John

      Related Posts

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Conducting Effective Post-Project Evaluations: A Guide

      December 16, 2024

      Strategies for Keeping Projects on Track and Meeting Deadlines

      December 10, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Programming January 12, 2016

      Работа с Git

      Основное на что хочу обратить внимание:
      1) Коммит должен четко соответствовать названию. А из названия должно быть понятно, что именно вы запушили.
      2) Хороший комммит умещается на экране, его не нужно долго листать, чтобы понять, что именно вы сделали.

      RxJs Practice

      April 26, 2017

      Data Science Overview: The Bigger Picture

      May 24, 2019

      Basic Prototype Design

      November 15, 2019

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      True Freelancer’s story

      Comics November 15, 2016

      Maximizing Efficiency: The Crucial Role of Lean Startup Methodology

      Startups November 26, 2024

      Top 10 Vue.js Interview Questions

      JavaScript February 9, 2019

      Building a Pokedex with Next.js

      JavaScript January 12, 2021

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Job

      Imposter Syndrome in Web Development: Understand It, Overcome It

      Express.js

      Profiling Tools and Techniques for Node.js Applications

      Tips

      Becoming a Technical Lead: Working on Your Leadership Skills

      Most Popular

      Strategies for Transforming Your Startup into a Profitable Venture

      Startups

      Уроки React. Урок 3

      Programming

      Top 5 Free Website Builders in 2019

      Tips
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.