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!
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;
}
...
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)
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>
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