事件阻止默认在 VueJS 实例中不起作用

新手上路,请多包涵

我试图在按下 回车 键时禁用表单提交。下面列出了我尝试过的方法以及代码和示例演示。

这里的问题示例

期望的结果: 专注于输入,按下 -> 向下 -> 输入,它应该记录你选择的记录的索引并停在那里。

实际发生了什么: 它按预期进行记录,但随后在表单提交时立即重新加载页面。

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=“阻止”
  • @提交
  • @提交.停止
  • @提交.prevent
  • @submit.stop.prevent=“预防”

我还尝试在 2 个事件处理程序中使用 with 调用以下内容,并从它们中返回 false。

  • 事件.preventDefault()
  • 事件.stopPropagation()

无论我尝试什么,表单仍然会触发页面重新加载。我看不出有什么明显的错误,所以我转向 stackoverflow 来指导我的眼睛。

谢谢

原文由 Kiee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 414
1 个回答

This Answer to another question 表明具有单个输入元素的表单总是被提交,不管你做什么。

确实添加另一个输入(并隐藏它)有所帮助。

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>

浏览器是愚蠢的。

原文由 Linus Borg 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题