Ad

Vue @click Doesn't Work On An Anchor Tag With Href Present

- 1 answer

EDIT: I forgot to clarify, what I'm looking for is to know how to write an anchor tag with the href attribute present but that when the element is clicked, the href should be ignored and the click handler should be executed.

I'm currently using Vue 1 and my code looks like:

<div v-if="!hasPage(category.code)">
  <div>
    <template v-for="subcategoryList in subcategoryLists[$index]" >
      <ul>
        <li v-for="subcategory in subcategoryList"v-on:click.stop="test()">
          <a :target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="subcategory.url">{{subcategory.label}}</a>
        </li>
      </ul>
    </template>
  </div>
</div>

What i'm trying to do is present the user with some buttons that represent my site's categories, some of this buttons will lead the user to another page and other will toggle a dropdown with a list of subcategories, when clicking these subcategories you will be taken to the subcategory's page.

These would be pretty simple but these buttons need to be tracked by Google Tag Manager so that's why I used the @click attribute to call a function and ignore the href attribute. This doesn't work, I have tried @click.prevent, @click.stop, @click.stop.prevent and none of these work.

The thing is that if I remove the href attribute, the @click method works great but an SEO requirement is to have href attributes on every link.

Any help would be appreciated.

Ad

Answer

As @dan-oswalt specified in the comments, you have to add the click event on the same element as the href. The reason it did not work the time you tried is most likely because you tried with @click.stop which only stops propagation, not the default action. (Redirect to the link). What you want is to prevent the browser to redirect the user: @click.prevent

new Vue({
  el: '#app',
  data: {
    subcategoryList: Array(10).fill({
        url: 'http://google.com',
        label: 'http://google.com'
    })
  },
  methods: {
    test(event) {
      event.target.style.color = "salmon"
    }
  }
})
Vue.config.devtools = false
Vue.config.productionTip = false
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<main id="app">
<template>
  <ul>
    <li v-for="subcategory in subcategoryList">
      <a :target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="subcategory.url" v-on:click.prevent="test($event)">{{subcategory.label}}</a>
    </li>
 </ul>
</template>
</main>

Ad
source: stackoverflow.com
Ad