1. 基础事件传参
(1) 模板中直接传递参数
<template>
<button @click="handleClick('Hello', 123)">点击传参</button>
</template>
<script>
export default {
methods: {
handleClick(msg, num) {
console.log(msg, num); // 输出: Hello 123
}
}
}
</script>
(2) 传递事件对象 ($event
)
如果需要同时传递参数和原生事件对象,使用 $event
:
<template>
<button @click="handleClick('Hello', $event)">点击传参</button>
</template>
<script>
export default {
methods: {
handleClick(msg, event) {
console.log(msg); // 输出: Hello
console.log(event.target); // 输出: <button>DOM 元素</button>
}
}
}
</script>
2. 组件自定义事件传参
(1) 子组件触发事件 ($emit
)
<!-- 子组件 Child.vue -->
<template>
<button @click="sendData">传递数据给父组件</button>
</template>
<script>
export default {
methods: {
sendData() {
this.$emit('custom-event', { name: 'Vue', id: 1 });
}
}
}
</script>
(2) 父组件接收事件
<!-- 父组件 Parent.vue -->
<template>
<Child @custom-event="handleCustomEvent" />
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child },
methods: {
handleCustomEvent(payload) {
console.log(payload.name); // 输出: Vue
console.log(payload.id); // 输出: 1
}
}
}
</script>