vue.js - VueJs - 表单提交时的 preventDefault()
问题描述
我需要以编程方式提交表单,但我也需要它preventDefault
。
现在我有以下内容:
submit() {
this.$refs.form.submit()
}
它工作正常,但我无法阻止提交的默认设置,最终刷新页面。
解决方案
简短的回答
您可以将.prevent
修饰符添加到(或您正在使用的@submit
任何其他),如下所示:v-on
<form @submit.prevent="myMethod">
<button type="submit"></button>
</form>
在提交表单的情况下,这将阻止刷新页面的默认行为。
长答案
有几种方法可以修改事件。
调用
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)
}
}
干杯:)
推荐阅读
- google-data-studio - 我正在尝试在 Google Data Studio 中绘制以下数据,但我无法
- c# - C# 有没有办法在代码中解析 lambda 表达式的委托类型
- reactjs - 防止来自内部重定向的预检请求
- sql - 获取 emolyee 的首要功能
- cqrs - 了解 CQRS 和 EventSourcing
- ios - 来自 xcode 11 的静态库在 xcode10 中不可接受是否正确
- java - 为什么我要多次获取数据?
- ruby-on-rails - Rails gem cancancan 不同可以吗?并授权
- javascript - 将数据发布到站点并将其加载到 iframe 中的另一个站点(角度和 c#)
- bash - Ansible:执行命令输出,进入另一个命令