简体   繁体   中英

Vue @click doesn't work on an anchor tag with href present

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 :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.

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/vue@2.5.17/dist/vue.js"></script> <main id="app"> <template> <ul> <li v-for="subcategory in subcategoryList"> <a :href="subcategory.url" v-on:click.prevent="test($event)">{{subcategory.label}}</a> </li> </ul> </template> </main> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM