我试图在按下 enter 键时禁用表单提交。下面列出了我尝试过的方法以及代码和示例演示。
期望的结果: 专注于输入,按下 -> 向下 -> 输入,它应该记录你选择的记录的索引并停在那里。
实际发生了什么: 它按预期进行记录,但随后会在表单提交时立即重新加载页面。
HTML
<form action="/some-action" @submit.stop.prevent="prevent">
<div class="auto-complete" v-cloak>
<div class="ico-input">
<input type="text" name="search" placeholder="Enter text" @keyup.prevent="handleKeypress">
</div>
<ul class="raw auto-complete-results">
<li v-for="r in results" @click="loadSelection($index)" v-bind:class="{'selected': selectedIndex == $index}"><span>{{ r.name }}</span></li>
</ul>
</div>
</form>
JS
var autocomplete = new Vue({
el: '.auto-complete',
data: {
results: [{name: 'swimming1'}, {name: 'swimming2'}, {name: 'swimming3'}, {name: 'swimming4'}, {name: 'swimming5'}, ],
selectedIndex: -1,
},
methods: {
handleKeypress: function(event) {
event.preventDefault();
event.stopPropagation();
var key = event.which;
if ([38, 40].indexOf(key) > -1) //handle up down arrows.
this.arrowNavigation(key);
else if (key == 13) //handle enter keypress
this.loadSelection(this.selectedIndex);
return false;
},
arrowNavigation: function(key, target) {
if (key == 38) //up
this.selectedIndex = this.selectedIndex - 1 < 0 ? 0 : this.selectedIndex - 1;
if (key == 40) //down
this.selectedIndex = (this.selectedIndex + 1) > (this.results.length - 1) ? 0 : this.selectedIndex + 1;
},
loadSelection: function(index) {
if (index < 0 || index > this.results.length)
return false;
var selection = this.results[index];
console.log("loading selection", index,selection);
},
prevent: function(event) {
event.preventDefault();
event.stopPropagation();
return false;
},
}
})
我已经在表单/输入上尝试了各种语法方法(在输入上将 submit
切换为 keyup
)
- v-on:submit="防止"
- @提交
- @submit.stop
- @submit.prevent
- @submit.stop.prevent="预防"
我还尝试在 2 个事件处理程序中使用 with 调用以下内容,并从它们中返回 false。
- event.preventDefault()
- event.stopPropagation()
无论我尝试什么,表单仍然会触发页面重新加载。我看不出任何明显的错误,所以我转向 stackoverflow 来指导我的眼睛。
谢谢
最佳答案
This Answer另一个问题表明,无论您做什么,具有单个输入元素的表单总是会被提交。
确实添加另一个输入(并隐藏它)有帮助。
https://jsfiddle.net/Linusborg/Lbq7hf1v/1/
<div class="ico-input">
<input type="text" name="search" placeholder="Enter text" @keyup.prevent="handleKeypress">
<input type="text" hidden style="display:none;">
</div>
浏览器是愚蠢的。
关于javascript - 事件阻止默认在 VueJS 实例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327809/