Javascript VueJS - 防止链接点击默认但也捕获对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30536571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VueJS - Prevent Default on link click but also capture object
提问by NightMICU
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):
我正在学习 Vue.JS 并且遇到了一些问题。我希望用户能够点击一个<a href="#"></a>标签e.preventDefault(),并抓取与链接关联的对象。这是我的代码(请注意,我在@前面是{{因为我使用的是 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:
和 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 responderobject but fires the link - I need to be able to both e.preventDefault()AND get the object.
就抓取responder对象但触发链接而言,这有效 - 我需要能够同时e.preventDefault()获取对象。
Thanks!
谢谢!
回答by nils
Alternatively, in Vue 1.x, you could also use the event modifier.prevent:
或者,在 Vue 1.x 中,您也可以使用事件修饰符.prevent:
HTML:
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:
JS:
...
showResponder: function(responder)
{
// No need to prevent any more
this.activeResponder = responder;
}
...
回答by Patrick Evans
The documentationshows 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() } } } /* ... */
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 属性是
v-on="click: showResponder(responder,$event)"
and the function definition to be
和函数定义是
showResponder: function(responder,e)

