본문 바로가기
Web/JavaScript

[Vue3] Handling Event using v-on

by llHoYall 2021. 6. 6.

You can handle events using v-on on Vue.

Create a Project

Let's create a project again to test an example.

2021.06.02 - [Web/JavaScript] - [Vue] Getting Started with Vue3 + TypeScript + TailwindCSS

And I recommend you read my previous Vue topics.

Click Event

Let's make a counter example.

This example has two buttons for an up and down counter. 

<h2 class="mb-2 text-xl font-medium text-green-600">Counter</h2>
<div>Value: {{ counter }}</div>
<div class="mt-2 flex">
  <button v-on:click="clickUp" class="btn mr-2">Up</button>
  <button @click="clickDown" class="btn">Down</button>
</div>
data: function () {
  return {
    counter: 0,
  };
},
methods: {
  clickUp: function () {
    this.counter += 1;
  },
  clickDown: function () {
    this.counter -= 1;
  },
},

At last, we make a function.

Every function should be in methods property.

You can access the variable through this in the function.

You can add functions to HTML tag via v-on directive or simply @.

Now, let's give parameters to a function.

<h2 class="mb-2 text-xl font-medium text-green-600">Counter</h2>
<div>Value: {{ counter }}</div>
<div class="mt-2 flex">
  <button v-on:click="clickUp(2)" class="btn mr-2">Up by 2</button>
  <button v-on:click="clickUp(1)" class="btn mr-2">Up</button>
  <button @click="clickDown" class="btn">Down</button>
</div>
clickUp: function (step: number) {
  this.counter += step;
},

Feel it how easy.

Key Event

You can also handle key events.

<h2 class="mt-8 mb-2 text-xl font-medium text-green-600">Key Event</h2>
<input
  v-on:keyup.enter="showAlert(1)"
  v-model="varStr"
  placeholder="Input enter key"
  class="px-2 rounded outline-none"
/>
<div>{{ varStr }}</div>
showAlert: function (mode: number) {
  if (mode === 1) {
    alert("<Enter> pressed");
  }
},

If you press the <ENTER> key in the input element, the alert window pops up.

This is the available key list.

  • .65 ~ .90 (A ~ Z)
  • .48 ~ .57 (0 ~ 9)
  • .space
  • .delete
  • .enter
  • .tab
  • .esc
  • .up / .right / .down / .left

You can also handle a key event with combining special keys.

<h2 class="mt-8 mb-2 text-xl font-medium text-green-600">Key Event</h2>
<input
  v-on:keyup.enter="showAlert(1)"
  v-model="varStr"
  placeholder="Input enter key"
  class="px-2 rounded outline-none"
/>
<input
  @keyup.enter.shift="showAlert(2)"
  v-model="varStr"
  placeholder="Input shift+enter key"
  class="mt-2 px-2 rounded outline-none"
/>
<div>{{ varStr }}</div>
showAlert: function (mode: number) {
  if (mode === 1) {
    alert("<Enter> pressed");
  } else if (mode === 2) {
    alert("<Shift+Enter> pressed");
  }
},

Press <SHIFT> + <ENTER> keys in the second input element and watch what will happen.

Below is the available key list.

  • .ctrl
  • .shift
  • .alt
  • .meta (Windows or Command)

You can combine multiple special keys.

댓글