iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
Vue.js

Vue.js 新手入門之路系列 第 10

Vue.js 新手入門之路 - 事件處理

  • 分享至 

  • xImage
  •  

今天要來學習 Vue 中的 event,使用的是 v-on,可簡解為 @

一個簡單內聯事件的例子

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

<script setup>
import { ref } from 'vue'
const attr = 'box'
const count = ref(0)

</script>

<style scoped>
    .box{
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: x-large;
        border: solid;
        margin-left: 650px;
        margin-top: 5px;
        height: 200px;
        width:350px;
        padding: 35px;
    }
</style>

按下按鈕後可使 count+1
https://ithelp.ithome.com.tw/upload/images/20250830/20178296qiHYH3xzC5.png

也可以將 v-on 綁定一個 function,再定義 function 要做的事情

<template>
  <div :class="attr">
    <button @click="greet">Greet</button>
    
  </div>
</template>

<script setup>
import { ref } from 'vue'
const attr = 'box'
const name = ref('Vue.js')

function greet(event) {
  alert(`Hello ${name.value}!`)
  if (event) {
    alert(event.target.tagName)
  }
}

</script>

<style scoped>
    .box{
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: x-large;
        border: solid;
        margin-left: 650px;
        margin-top: 5px;
        height: 200px;
        width:350px;
        padding: 35px;
    }
</style>

https://ithelp.ithome.com.tw/upload/images/20250830/20178296YBwDXdFoUB.png
透過 event.target.tagName 訪問觸發事件的元素
https://ithelp.ithome.com.tw/upload/images/20250830/20178296qrvROdwK7k.png


上一篇
Vue.js 新手入門之路 - 清單渲染 (二)
下一篇
Vue.js 新手入門之路 - 事件處理(二)
系列文
Vue.js 新手入門之路15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言