Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - Prevent Default on link click but also capture object

I am learning Vue.JS and have run into a bit of a problem. I want the user to be able to click on an <a href="#"></a> tag, e.preventDefault(), and also grab the object associated with the link. Here is my code (note that I have @ preceding the {{ because I am using Blade):

<a href="#"
   class="list-group-item"
   v-repeat="responder: responders"
   v-on="click: showResponder(responder)">
    <div class="media">
        <div class="media-left">
            <img src="" v-attr="src: responder.avatar" alt="" class="media-object"/>
        </div>
        <div class="media-body">
            <h4 class="media-heading">@{{ responder.first_name }} @{{ responder.last_name }}</h4>
            <p>
                <strong><i class="fa fa-phone"></i> Phone:</strong> @{{ responder.phone }}
            </p>
        </div>
    </div>
</a>

And the Javascript:

var vm = new Vue({
    el: "#responderContainer",
    data: {
        activeResponder: null,
        responders: []
    },
    methods: {
        showResponder: function(responder)
        {
            // Here is where I wish to prevent the 
            // link from actually firing its default action
            responder.preventDefault();
            this.activeResponder = responder;
        }
    }
});

This works as far as grabbing the responder object but fires the link - I need to be able to both e.preventDefault() AND get the object.

Thanks!

like image 763
NightMICU Avatar asked May 29 '15 18:05

NightMICU


3 Answers

Alternatively, in Vue 1.x, you could also use the event modifier .prevent:

HTML:

<a v-on:click.prevent="showResponder(responder)">...</a>

You could stop propagation as well:

<a v-on:click.prevent.stop="showResponder(responder)">...</a>

JS:

...
            showResponder: function(responder)
            {
                // No need to prevent any more
                this.activeResponder = responder;
            }
...
like image 157
nils Avatar answered Nov 18 '22 19:11

nils


The documentation shows you can pass $event to get the event object

http://vuejs.org/guide/events.html

<button v-on="click: submit('hello!', $event)">Submit</button>

/* ... */
{
  methods: {
    submit: function (msg, e) {
      e.stopPropagation()
    }
  }
}
/* ... */

So you want the v-on attribute to be

v-on="click: showResponder(responder,$event)"

and the function definition to be

showResponder: function(responder,e)
like image 42
Patrick Evans Avatar answered Nov 18 '22 19:11

Patrick Evans


Use

@click.stop

on a parent element to stop event bubbling if you want to use href and not the custom click events.

<div @click.stop>
  <a href="//google.ca">Google</a>
</div>
like image 2
Ahmad Avatar answered Nov 18 '22 18:11

Ahmad