VueJS: @click.native.stop = "" possible?

DmitrySemenov picture DmitrySemenov · Mar 1, 2018 · Viewed 13.4k times · Source

I have several nested components on the page with parents component having @click.native implementation. Therefore when I click on the area occupied by a child component (living inside parent), both click actions executed (parent and all nested children) for example

<products>
   <product-details>
       <slide-show>
             <media-manager>
                  <modal-dialog>
   <product-details>
       <slide-show>
             <media-manager>
                  <modal-dialog>
 </products>

So I have a list of multiple products, and when I click on "canvas" belonging to modal dialog - I also get @click.native fired on product-details to which modal-dialog belongs. Would be nice to have something like @click.native.stop="code", is this possible?

Right now I have to do this:

@click.native="clickHandler"
and then 

  methods: {
    clickHandler(e) {
      e.stopPropagation();
      console.log(e);
    }

code

<template>
  <div class="media-manager">
    <div v-if="!getMedia">
      <h1>When you're ready please upload a new image</h1>
      <a href="#"
         class="btn btn--diagonal btn--orange"
         @click="upload=true">Upload Here</a>
    </div>
    <img :src="getMedia.media_url"
         @click="upload=true"
         v-if="getMedia">
    <br>
    <a class="arrow-btn"
       @click="upload=true"
       v-if="getMedia">Add more images</a>
    <!-- use the modal component, pass in the prop -->
    <ModalDialog
      v-if="upload"
      @click.native="clickHandler"
      @close="upload=false">
      <h3 slot="header">Upload Images</h3>
      <p slot="body">Hello World</p>
    </ModalDialog>
  </div>
</template>

<script>
import ModalDialog from '@/components/common/ModalDialog';
export default {
  components: {
    ModalDialog,
  },
  props: {
    files: {
      default: () => [],
      type: Array,
    },
  },
  data() {
    return {
     upload: false,
    }
  },
  computed: {
    /**
     * Obtain single image from the media array
     */
    getMedia() {
      const [
        media,
      ] = this.files;

      return media;
    },
  },
  methods: {
    clickHandler(e) {
      e.stopPropagation();
      console.log(e);
    }
  }
};
</script>

<style lang="scss" scoped>
.media-manager img {
  max-width: 100%;
  height: auto;
}

a {
  cursor: pointer;
}

</style>

Answer

nara_l picture nara_l · Mar 20, 2018

Did you check the manual? https://vuejs.org/v2/guide/events.html

There is @click.stop="" or @click.stop.prevent=""

So you don't need to use this

methods: {
    clickHandler(e) {
      e.stopPropagation();
      console.log(e);
    }
  }