DOM 事件传参

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值