click.stop prevents events from bubbling up

`click` and `click.stop` are event modifiers used to handle mouse click events. The difference is:

- The ` click ` modifier is used to listen for mouse click events and trigger the corresponding processing function. If `event.preventDefault()` is used in the handler function, the default behavior will be prevented, such as preventing form submission or link jump.

- The ` click.stop ` modifier is also used to listen for mouse click events and trigger the corresponding processing function. However, it prevents the event from continuing to propagate, i.e. it prevents the event from bubbling up to the parent element. This means that if you use the `click.stop` modifier on a nested element, when the element is clicked, the handler on the element will be fired, but the event will not continue to the parent element. .

For example, the following code (Vue version) demonstrates how to use the `click` modifier on a button to prevent form submission:


<template>
  <form @submit.prevent="submitForm">
    <button type="submit" @click.prevent="submitForm">Submit</button>
  </form>
</template>

<script>
export default {
  methods: {
    submitForm() {
      // 处理表单提交逻辑
    }
  }
}
</script>

In the above code, when the user clicks the "Submit" button, the `submitForm` method is called and the `prevent` modifier is used to prevent form submission.

The following code demonstrates how to use the `click.stop` modifier on a nested element to prevent the event from bubbling:

<template>
  <div @click="handleClick">
    <button @click.stop>Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      console.log('Div clicked');
    }
  }
}
</script>

In the above code, when the user clicks the "Click me" button, only the handler function on the button will be triggered, not the handler function on the parent element. Therefore, the console will only output "Div clicked" once.

Guess you like

Origin blog.csdn.net/dongnihao/article/details/131899307