Vue.js: How to prevent browser from going to href link and instead only execute the @click method?

前端 未结 2 1872
梦毁少年i
梦毁少年i 2021-01-07 15:58

So I have a link in my application like this:

My first thread

A

相关标签:
2条回答
  • 2021-01-07 16:16

    You are looking for .prevent modifer.

    <a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
    
    0 讨论(0)
  • 2021-01-07 16:20

    See Event Handling in the guide:

    Event Modifiers

    It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers. Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

    To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

    .stop
    .prevent
    .capture
    .self
    .once
    .passive

    So:

    <a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
    <!-- -------------------------------------^^^^^^^^                    --->
    

    ...or of course, accept the event parameter and call preventDefault.

    Live Example on jsFiddle (since Stack Snippets don't allow off-site links).

    0 讨论(0)
提交回复
热议问题