vue @click 与 原生 onclick 对比

1,586 阅读1分钟

触发事件的元素对象的传递

原生无法传递事件,只能通过this指针,传递触发事件的对象,即元素

<!DOCTYPE html>
<html>
<body>
<button onclick="handleClick(this)">click</button>

<script>
function handleClick(el) {
  console.log(el)//得到触发事件的元素对象
}
</script>

</body>
</html>

如果vue也传递this呢?

<script setup>
function handleClick(proxy) {
  console.log(proxy)
}
</script>

<template>
<div>
  <button 
    @click="handleClick(this)"
  >
  click
  </button>

</div>
</template>
<style>
div {
  height: 100vh;
}
button {
  @apply btn-info
}
</style>

会得到一个proxy,里面有一堆$开头的东西

image-20220701154032-zx11yp5.png

那个$el是不是就是元素?

<script setup>
function handleClick(el) {
  console.log(el)
}
</script>

<template>
<div>
  <button 
    @click="handleClick($el)"
  >
  click
  </button>

</div>
</template>
<style>
div {
  height: 100vh;
}
button {
  @apply btn-info
}
</style>

发现得到元素

试试其他的

<script setup>
function handleClick(event) {
  console.log(event)
}
</script>

<template>
<div>
  <button 
    @click="handleClick($event)"
  >
  click
  </button>

</div>
</template>
<style>
div {
  height: 100vh;
}
button {
  @apply btn-info
}
</style>

这样得到了事件,其他的以此类推

是否可以函数嵌套表达

原生可以函数嵌套表达

<!DOCTYPE html>
<html>
<body>
<button onclick="handleClick(console.log('1'))">click</button>

<script>
function handleClick() {
  console.log('2')
}
</script>

</body>
</html>

而vue不可以

<script setup>
function handleClick() {
  console.log('2')
}
</script>

<template>
<div>
    <button 
      onclick="handleClick(console.log('1'))"
    >
    click
    </button>
</div>
</template>

最开始我做函数防抖时, @click 里直接写上防抖函数, 然后传入要防抖的函数, 一直搞不明白为什么错了

ps:如果要防抖节流推荐用vueuse里的useDebounceFn和useThrottleFn

最后注意一下在 vue 中无法使用原生的 onclick

<script setup>
function handleClick() {
  console.log('1')
}
</script>

<template>
<div>
    <button 
      onclick="handleClick()"
    >
    click
    </button>
</div>
</template>

会报错,说函数handleClick未定义