在Vue 3中,你可以使用@click指令来监听元素的点击事件。这可以通过在模板中直接使用@click指令或在JavaScript中使用v-on指令来完成。

以下是在Vue 3中监听元素点击事件的几种方法:

  1. 在模板中使用@click指令:
<template>
  <button @click="handleClick">点击我</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      console.log('按钮被点击了');
    }
  }
}
</script>
  1. 在JavaScript中使用v-on指令:
<template>
  <button ref="myButton">点击我</button>
</template>

<script>
export default {
  mounted() {
    const button = this.$refs.myButton;
    button.addEventListener('click', this.handleClick);
  },
  beforeUnmount() {
    const button = this.$refs.myButton;
    button.removeEventListener('click', this.handleClick);
  },
  methods: {
    handleClick() {
      console.log('按钮被点击了');
    }
  }
}
</script>
  1. 使用@click指令和内联JavaScript:
<template>
  <button @click="() => handleClick('参数')">点击我</button>
</template>

<script>
export default {
  methods: {
    handleClick(param) {
      console.log('按钮被点击了,参数为:', param);
    }
  }
}
</script>

这些方法中,第一种和第三种是最常用的。第二种方法适用于在Vue组件中使用传统的JavaScript事件监听器。

vue3 setup 元素點擊事件怎麼在js中監聽

原文地址: http://www.cveoy.top/t/topic/jdai 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录