VueJs - 表单提交时的 preventDefault() [英] VueJs - preventDefault() on form submission

查看:33
本文介绍了VueJs - 表单提交时的 preventDefault()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式提交表单,但我也需要它来preventDefault.

I need to submit a form programmatically, but I need it to preventDefault as well.

现在我有以下几点:

submit() {
  this.$refs.form.submit()
}

它工作正常,但我无法阻止提交的默认值,最终刷新页面.

It is working fine, but I cannot prevent default on the submit which in the end, refreshes the page.

推荐答案

有几种方法可以修改事件.

There are several ways to modify events.

来自 Vue 文档:

调用 event.preventDefault()event.stopPropagation() 在事件处理程序中.虽然我们可以做到这一点很容易在方法内部,如果方法可以纯粹是更好的关于数据逻辑,而不必处理 DOM 事件细节.

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.

为了解决这个问题,Vue 为 v-on 提供了事件修饰符.记起修饰符是用点表示的指令后缀.

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

<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="doThis"></a>

<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- just the modifier -->
<form v-on:submit.prevent></form>

<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>

<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>

另一种选择:

有时我们还需要在内联语句处理程序中访问原始 DOM 事件.您可以使用特殊的 $event 变量将其传递给方法:

Sometimes we also need to access the original DOM event in an inline statement handler. You can pass it into a method using the special $event variable:

<button v-on:click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>

// ...
methods: {
  warn: function (message, event) {
    // now we have access to the native event
    if (event) {
      event.preventDefault()
    }
    alert(message)
  }
}

干杯:)

这篇关于VueJs - 表单提交时的 preventDefault()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆