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

时间:2016-07-12 11:36:59

标签: javascript vue.js preventdefault

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

EXAMPLE OF PROBLEM HERE

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

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

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 for keyup

  • v-on:submit =“prevent”
  • @submit
  • @ submit.stop
  • @ submit.prevent
  • @ submit.stop.prevent = “预防”

我也试过在2个事件处理程序中调用以下内容以及从它们返回false。

  • event.preventDefault()
  • event.stopPropagation()

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

由于

1 个答案:

答案 0 :(得分:3)

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>

浏览器是愚蠢的。