VueJs - 表单提交时的 preventDefault()

新手上路,请多包涵

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

现在我有以下内容:

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

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

原文由 Malthe Bjerregaard Petersen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 575
1 个回答

简答

您可以将 .prevent 修饰符添加到 @submit (或您正在使用的任何其他 v-on ),如下所示:

 <form @submit.prevent="myMethod">
  <button type="submit"></button>
</form>

在提交表单的情况下,这将阻止刷新页面的默认行为。

长答案

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

来自 Vue 3 文档

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

为了解决这个问题,Vue 为 v-on 提供了事件修饰符。回想一下,修饰符是由点表示的指令后缀。

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

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

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

<!-- just the modifier -->
<form @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 @click.capture="doThis">...</div>

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

另一种选择

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

 <button @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)
  }
}

干杯 :)

原文由 pitamer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏