VueJS - 阻止链接默认行为但仍能捕获对象

31

我正在学习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>

还有 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;
        }
    }
});

这个方法可以获取responder对象,但是会触发链接 - 我需要既能e.preventDefault()又能获取对象。

谢谢!

3个回答

62

在 Vue 1.x 中,你也可以使用 event modifier.prevent

HTML:

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

你也可以停止事件传播:

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

JS:

...
            showResponder: function(responder)
            {
                // No need to prevent any more
                this.activeResponder = responder;
            }
...

7
应该正确使用 v-on:click.prevent - Mladen Danic
4
在没有可调用的方法(例如一个简单的<a href="mailto:someone@example.org">链接)时,如何防止事件传播? - Adam Reis
2
针对@MladenDanic的问题, prevent将会阻止默认行为,而prevent.stop将会同时停止事件传播。例如:如果您正在触发下拉菜单导航中锚点点击的自定义方法,则prevent.stop还将阻止'click'事件,使得下拉菜单保持打开状态。prevent将会停止锚链接,但允许事件向上传播以执行'click'行为。 - iamface
@AdamReis 在我的情况下,我想防止在单击没有方法的 'href时单击table中的tr。我在 'td 中使用了.self,并将方法从 tr 移动到每个 td。看看这个:https://dev59.com/fsHqa4cB1Zd3GeqP7s-O#74465289 - JotaPardo

32

这个 文档 展示了你可以通过传递 $event 来获取事件对象。

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

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

/* ... */
{
  methods: {
    submit: function (msg, e) {
      e.stopPropagation()
    }
  }
}
/* ... */
所以您希望v-on属性是:
v-on="click: showResponder(responder,$event)"

并且函数定义为

showResponder: function(responder,e)

4

使用

@click.stop

在父元素上使用阻止事件冒泡,如果你想使用 href 而不是自定义的点击事件。
<div @click.stop>
  <a href="//google.ca">Google</a>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接