DOM events and v-on
We can handle DOM events within Vue by using v-on
. By listening to DOM events, we're able to react to user input with everything from key-down events (such as clicking the Enter button) to button click events and more.
Let's make a playground project to try this in our own project:
# Create a new Vue project $ vue init webpack-simple vue-on # Navigate to directory $ cd vue-on # Install dependencies $ npm install # Run application $ npm run dev
Let's imagine an input
box such that, when we either hit the Add
button or hit the Enter key, the input gets added to an array:
<template> <div id="app"> <ul> <li v-for="(p, index) in person" :key="index"> {{p}} </li> </ul> <input type="text" v-model="person" v-on:keyup.enter="addPerson" /> <button v-on:click="addPerson">Add {{ person}} </button> </div> </template> <script> export default { name: 'app', data () { return { person: ...