Search code examples
javascriptvue.jsvuetify.jsstoppropagation

How to avoid @click on only one child component


For example if I click on all the v-card I am redirecting to an other link BUT if I click on the title World of the Day and only on the title I don't want to do nothing. How to avoid to be redirected when clicking on title ?

enter image description here

template>
  <v-card
    class="mx-auto"
    max-width="344"
    @click="goToAnOtherLink"
  >
    <v-card-text>
      <div>Word of the Day</div>
      <p class="display-1 text--primary">
        be•nev•o•lent
      </p>
      <p>adjective</p>
      <div class="text--primary">
        well meaning and kindly.<br>
        "a benevolent smile"
      </div>
    </v-card-text>
    <v-card-actions>
      <v-btn
        text
        color="deep-purple accent-4"
      >
        Learn More
      </v-btn>
    </v-card-actions>
  </v-card>
</template>

Solution

  • Add a class to the title div as well, and check the classes of your event's target inside the function goToAnOtherLink. Then you can use stopPropagation() along with the custom code you have in that function.

    new Vue({
      el: "#app",
      data() {},
      methods: {
        goToAnOtherLink(e) {
          if (e.target.classList.contains("title") || e.target.classList.contains("display-1")) {
            e.stopPropagation()
            console.log("Cancelled Navigation!")
          } else {
            console.log("Navigated!")
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" />
    
    <div id="app">
      <v-app>
        <v-card class="mx-auto" max-width="344" @click="goToAnOtherLink">
          <v-card-text>
            <div class="title">Word of the Day</div>
            <p class="display-1 text--primary">
              be•nev•o•lent
            </p>
            <p>adjective</p>
            <div class="text--primary">
              well meaning and kindly.<br> "a benevolent smile"
            </div>
          </v-card-text>
          <v-card-actions>
            <v-btn text color="deep-purple accent-4">
              Learn More
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-app>
    </div>