input
组件上按回车后阻止 form
表单默认的提交, 同时执行自己定义的提交方法form
表单直接被提交el-input
添加一个keyup的事件, 自行管理默认行为<template>
<el-form :inline="true">
<el-form-item>
<el-input v-model="form.username" placeholder="请输入用户名" @keyup.enter.prevent="onSubmit"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data () {
return {
form: {
username: ''
}
}
},
methods: {
onSubmit () {
alert('submit')
}
}
}
</script>
PS: 官网上的例子如果存在多个表单选项, 输入回车后并不会自动submit, 然而出现单个 input组件的时候, 聚焦input
后按回车就会触发自动提交。 官网demo地址
这是 form 标签的默认行为,在 <el-form>
标签上加 @submit.native.prevent
就行。
@Leopoldthecoder 恩, 你说的没错. 在el-form
使用 @submit.native.prevent
可以阻止原生form
默认行为, 不过还是无法监听el-input
的 keyup
事件
看 FAQ 第一条。
明白了, 谢谢:)
PS: 官网上的例子如果存在多个表单选项, 输入回车后并不会自动submit, 然而出现单个 input组件的时候, 聚焦input后按回车就会触发自动提交。
以上,是否可以视为 Bug 呢,还是出于什么考虑?毕竟表单项的回车提交是一个默认行为,却因为表单项的多寡而有所不同,这同时也叫人困惑,如果不是 @liyanlong 提出,我还在郁闷到底为何我的两个组件的表单回车不一致。
主要是我这里只是需要监听回车键,那么有如每个 input 都监听keyup,还不如直接监听 form 的 submit 事件。所以,如何才能开启多个表单项的时候,回车的默认提交行为呢?
谢谢。
@Riant 同疑惑!
难怪我测了好久都没有办法用回车直接提交表单
@Riant
毕竟表单项的回车提交是一个默认行为,却因为表单项的多寡而有所不同,这同时也叫人困惑
这是浏览器的默认行为,与 Element 和 Vue 都无关:
只有一个 input:https://jsfiddle.net/rswut6kk/
有两个 input:https://jsfiddle.net/rswut6kk/1/
@Leopoldthecoder
谢谢,哈哈,看来还是 HTML 基础不好啊。
经过进一步尝试、测试,在表单中加 type=submit 的 input 或者 button(type=‘submit’ 或者不定义 type 属性) ,input 中回车浏览器就会直接提交了。
https://jsfiddle.net/rswut6kk/2/
@funkyLover
所以这个问题算是解决了:给 el-form 表单中的 button 定义 native-type='submit' 或者 使用原生的 input(type='submit) 作为提交按钮。
当然还有一个细节,未定义 type 的 button 在浏览器中默认是 submit 的行为,所以 element 的 button 组件,native-type 不设置的情况下,最好还是不设置其 button 原生 type 属性,这样就比较符合原生习惯了。也就不会出现上面我们讨论的这个问题了。
@Riant
测试发现只要input='text'
被form包起来,focus
---input回车表单就会提交和有没有submit
按钮没关系。
以上提供的native-type='submit'
是有效果的;
只是不知道Element对form做了什么~_-
@jinglf000
不,多个 input ,即使被 form 包起来,如果没有 input:submit 按钮或者 button type 不等于 submit 的话,focus input:text 回车并不会提交表单,参考示范 https://jsfiddle.net/rswut6kk/3/
嗯嗯,这就解释了,form中单个input:text和多个input在Element form表单下的差异,
2017-07-12 10:54 GMT+08:00 Riant notifications@github.com:
@jinglf000 https://github.com/jinglf000
不,多个 input ,即使被 form 包起来,如果没有 input:submit 按钮或者 button type 不等于 submit
的话,focus input:text 回车并不会提交表单,参考示范 https://jsfiddle.net/rswut6kk/3/—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/ElemeFE/element/issues/3625#issuecomment-314630217,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ANiZcQspYGKrJVAwo6a3mJJH3lJ1o9XEks5sNDVYgaJpZM4MiPV8
.
use native-type='submit'
,like that:
Most helpful comment
这是 form 标签的默认行为,在
<el-form>
标签上加@submit.native.prevent
就行。