在 Vue 中获取点击元素的 ID 方法有:使用 ref 和 $refs使用 v-on:click 和 $event使用原生 JavaScript

如何在 Vue 中获取点击元素的 ID
在 Vue 中获取点击元素的 ID 有多种方法:
1. 使用 ref 和 $refs
<code class="html"><template>
<button ref="myButton" @click="handleClick">Click Me</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log(this.$refs.myButton.id);
}
}
};
</script></code>2. 使用 v-on:click 和 $event
立即学习“前端免费学习笔记(深入)”;
<code class="html"><template>
<button @click="handleClick">Click Me</button>
</template>
<script>
export default {
methods: {
handleClick(event) {
console.log(event.target.id);
}
}
};
</script></code>3. 使用原生 JavaScript
<code class="html"><template>
<button @click="handleClick">Click Me</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log(this.id);
}
},
mounted() {
this.$el.addEventListener('click', this.handleClick);
}
};
</script></code>选择最合适的方法:
选择哪种方法取决于具体情况:
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号