VueJs - 表单提交时的 preventDefault()

Mal*_*sen 8 vue.js

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

现在我有以下几点:

submit() {
  this.$refs.form.submit()
}
Run Code Online (Sandbox Code Playgroud)

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

pit*_*mer 32

简短回答

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

<form @submit.prevent="myMethod">
  <button type="submit"></button>
</form>
Run Code Online (Sandbox Code Playgroud)

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

长答案

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

来自 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>
Run Code Online (Sandbox Code Playgroud)

另外一个选择

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

<button @click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>
Run Code Online (Sandbox Code Playgroud)
// ...
methods: {
  warn: function (message, event) {
    // now we have access to the native event
    if (event) {
      event.preventDefault()
    }
    alert(message)
  }
}
Run Code Online (Sandbox Code Playgroud)

干杯:)


Abe*_*llo 8

不太明白@Armin Ayari的答案,例如为什么代码必须位于对象中methods?无论如何,在 Vue 中,这对我有用:

<form ref="form" @submit.prevent="myMethod">
  <button type="submit"></button>
</form>
Run Code Online (Sandbox Code Playgroud)

这会阻止页面刷新并调用myMethod

你甚至不需要ref. 了解这是一个老问题,但我在调试后发现自己在这里,并发现我的表单标签只是放错了位置。


Arm*_*ari 1

我不知道我是否正确理解了你的问题,但你可以像这样阻止表单的默认行为:

this.$refs.form.addEventListener("submit", (event) => {
    event.preventDefault()
});
Run Code Online (Sandbox Code Playgroud)

也许这可以帮助你:

this.$refs.form.addEventListener("submit", (event) => {
    event.preventDefault()
});
Run Code Online (Sandbox Code Playgroud)
new Vue({
  el: '#app',
  data: {},
  methods: {
    submit () {
      this.$refs.form.addEventListener('submit', event => {
        event.preventDefault()
      })
    },
    alert () {
      alert('hello')
    }
  }
})
Run Code Online (Sandbox Code Playgroud)