MST

星途 面试题库

面试题:Vue中如何处理父子组件间事件冲突

在Vue项目里,父组件和子组件都绑定了针对同一DOM元素的点击事件,例如都对一个按钮有点击处理逻辑,但是希望父组件的点击事件在子组件点击事件之后触发,你会如何实现?
18.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 使用事件冒泡机制
    • 在子组件中,按钮的点击事件处理函数正常编写。在处理完子组件逻辑后,事件会冒泡到父组件。
    • 父组件在模板中监听来自子组件冒泡的点击事件。例如:
    <!-- 子组件模板 -->
    <template>
      <button @click="handleChildClick">子组件按钮</button>
    </template>
    <script>
    export default {
      methods: {
        handleChildClick() {
          // 子组件点击处理逻辑
          console.log('子组件点击事件处理');
        }
      }
    };
    </script>
    
    <!-- 父组件模板 -->
    <template>
      <child - component @click="handleParentClick"></child - component>
    </template>
    <script>
    import ChildComponent from './ChildComponent.vue';
    export default {
      components: {
        ChildComponent
      },
      methods: {
        handleParentClick() {
          // 父组件点击处理逻辑
          console.log('父组件点击事件处理');
        }
      }
    };
    </script>
    
  2. 使用$nextTick
    • 在子组件中,点击事件处理函数里使用$nextTick来延迟父组件点击事件的触发。
    • 例如:
    <!-- 子组件模板 -->
    <template>
      <button @click="handleChildClick">子组件按钮</button>
    </template>
    <script>
    export default {
      methods: {
        handleChildClick() {
          // 子组件点击处理逻辑
          console.log('子组件点击事件处理');
          this.$nextTick(() => {
            this.$emit('parent - click');
          });
        }
      }
    };
    </script>
    
    <!-- 父组件模板 -->
    <template>
      <child - component @parent - click="handleParentClick"></child - component>
    </template>
    <script>
    import ChildComponent from './ChildComponent.vue';
    export default {
      components: {
        ChildComponent
      },
      methods: {
        handleParentClick() {
          // 父组件点击处理逻辑
          console.log('父组件点击事件处理');
        }
      }
    };
    </script>