今天要來學習 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
也可以將 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>
透過 event.target.tagName
訪問觸發事件的元素