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.
Do not use an anchor with an onclick event without an href element event.
You can now link to this section (div) using the anchor tag. To do that, just use the id of the section with a # as the prefix for the href value. So, when you click on the Go link, you will scroll to the news section of the page. Demonstration of the in-page link.
Vue (pronounced /vjuː/, like view) is a JavaScript framework for building user interfaces. It builds on top of standard HTML, CSS and JavaScript, and provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be it simple or complex.
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 :href="subcategory.url" v-on:click.prevent="test($event)">{{subcategory.label}}</a>
</li>
</ul>
</template>
</main>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With