我需要以编程方式提交表单,但我也需要它来preventDefault
。
现在我有以下内容:
submit() {
this.$refs.form.submit()
}
它工作正常,但我无法阻止提交时的默认设置,最终会刷新页面。
最佳答案
简答
您可以将 .prevent
修饰符添加到 @submit
(或您正在使用的任何其他 v-on
),如下所示:
<form @submit.prevent="myMethod">
<button type="submit"></button>
</form>
在提交表单的情况下,这将阻止刷新页面的默认行为。
长答案
有几种方法可以修改事件。
It is a very common need to call
event.preventDefault()
orevent.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.
<!-- 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>
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 @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)
}
}
干杯:)
关于vue.js - VueJs - 表单提交时的 preventDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51732051/