Click event renders an element, and clicks it simultaneously

Hello,

I have a hidden link, and a link which hides itself when clicked, and renders the hidden link at the same spot it was. However, when I click that link, the hidden link gets rendered but also get clicked on at the same time, which is a big problem for what I’m doing.

Here’s a very simple code demonstrating this: https://jsfiddle.net/5fjevwxs/
Just in case, I’ll include the code here too:

<div id="app">
  <a v-if="!foo" v-on:click="foo = true">Show link</a>
  <a v-if="foo" href="" >link</a>
</div>
var app = new Vue({
  el: '#app',
  data: {
    foo: false,
  }
})

As you can see, when “Show link” gets clicked, “link” also get clicked, and it reloads the page.

What would be a good way to prevent that ?
Thank you

This is actually an issue with using an empty href attribute. If you remove the attribute or set it to # or an actual url then you won’t have this problem.

https://jsfiddle.net/jamesbrndwgn/dxpLgve2/1/

Removing it works, but putting a href, whether empty or non-empty always seems to trigger the link on my side. Even putting a “#” will trigger the link and add “#” to the link.

Gotcha. Was hard to see that in jsfiddle.

Much easier in Codepen debug: https://cdpn.io/getreworked/debug/oNjmEQY/vPMKKeRbjgVM

The problem has to do with Vue’s diffing. In order to optimize DOM replacement it’s using the same anchor tag because as far as Vue is concerned it’s the same, but with a few alterations. To help inform Vue that the whole element should be replaced with a new one you’ll want to use the key attribute.

  <a v-if="!foo" v-on:click="foo = true" key="1">Show link</a>
  <a v-else href="#" key="2">link</a>

Updated code: https://codepen.io/getreworked/pen/oNjmEQY

2 Likes

try with this

    <div id="app">
          <a v-if="!foo" v-on:click.prevent="foo = true">Show link</a>
          <a v-else href="" >link</a>
        </div>