关于组件button里面处理click事件

来源:7-8 通用组件:button 按钮功能实现-2

一只小木马

2022-09-05

按照老师您的方法处理了click事件,但是在search组件中绑定click时,点击button,这个事件触发了两次 我猜测一次是在search组件中因为点击了button,触发了一次 还有一次是传入到button中,然后通过emit又触发了一次
而且我给button组件设置loading,这个click事件也还是出发了一次(search组件中因为点击了button),所以有点不明白是怎么回事
通用组件button

<button 
        class="text-sm text-center flex justify-center items-center duration-200"
        :class="[
            typeEnum[type],
            sizeEnum[size],
            shapeEnum[shape],
            selfClass,
            {'active:scale-105':isAnimated}
        ]"
        @click.stop="onBtnClick"
    >
    ...
</button>
<script>
	 // handle click event
    const emits = defineEmits(['click'])
    const onBtnClick=()=>{
        // if lodading, return
        if(props.loading){
            return
        }
        emits('click');
    }
</script>

Search组件中

<!--search button-->
    <button-vue
        class="absolute right-1"
        size="large" 
        shape="circle"
        icon="search"
        :loading="true"
        @click="Click"
    >
        Search
    </button-vue>

<script>
// handle click
const Click=()=>{
    console.log('click')
}
</script>
写回答

1回答

Sunday

2022-09-05

你好

按照你当前的代码逻辑,button 组件内部使用了 stop 禁止冒泡,并且通过 @ 监听了 click 事件,那么事件就会被拦截,通过 emits 发送出去,那么这个事件是不会被两次触发的。他只会被 emit 一次。

0
1
一只小木马
好的老师我明白了 我今天重启了一下项目就没问题了
2022-09-06
共1条回复

基于 Vue3 ,打造前台+中台通用开发提效解决方案

42 种前台常见业务模型, 15 种中台通用组件,成为前端提效高手

788 学习 · 517 问题

查看课程