keyboard_tabSkip to content
listVue Firebase Masterclass

แนะนำ Event

สารบัญ

Document ต้นฉบับ: https://vuejs.org/guide/essentials/event-handling.html

วิธีการเทียบ Event ใน Javascript ปกติกับ Vue Event

  • onclick="functionName()" ใน javascript
  • มีค่าเทียบเท่ากับ v-on:click="functionName()"
  • หรือเทียบเท่ากับ @click="functionName()"

ซึงวิธีการ binding event มีทั้งหมด 2 ประเภทคือ

  1. Inline handler = การใส่ inline javascript เพื่อเพิ่ม function ให้ trigger event
  2. Method handler = เป็นการระบุ property หรือ path ที่ชี้สู่ method ใน Component ของ Event

ตัวอย่าง binding Event

1. Inline handler

html
<script setup>
const count = ref(0)
</script>

<template>
  <div>
    <button @click="count++">Add 1</button>
    <p>Count is: {{ count }}</p>
  </div>
</template>

2. Method handler

html
<script setup>
const name = ref('Vue.js')

const greet = (event) => {
  alert(`Hello ${name.value}!`)
  // `event` is the native DOM event
  if (event) {
    alert(event.target.tagName)
  }
}
</script>

<template>
  <button @click="greet">Greet</button>
</template>

มาลองดู Event อื่นๆกัน

เราจะลองทำจากการ change ผ่าน input บ้าง

  • ใช้ event oninput สำหรับดักจับ input change
  • ใน vue event ก็จะเปลี่ยนเป็น @input และเราก็จะทำการผูก name เข้ากับ input
html
<script setup>
import { ref } from 'vue'
const name = ref('')

const onInput = (event) => {
  name.value = event.target.value
}
</script>
<template>
  <div>
    <input type="text" :value="name" @input="onInput">
    <p>Hello, {{ name }}!</p>
  </div>
</template>