如何使用回车键将项目添加到输入中,仅在单击按钮时提交表单?

时间:2017-09-29 15:56:45

标签: javascript vue.js vuejs2 vue-component v-select

我使用v-select并且此插件存在问题...当您在输入中按输入时,它会提交到表单。如何使用回车添加项目以进行输入,仅在我点击按钮时提交表单?

Example Here CODE PEN

HTML

<div id="app">
  <h1>Vue Select</h1>
  <p>Try to add items in input using "ENTER"</p>
  <form v-on:submit.prevent="submited()">
  <v-select multiselect :options="options"></v-select>
    <button type="submit">Submit</button>
  </form>
</div>

JS

Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    options: ["some", "thing", "another", "things"]
  },
  methods: {
    submited(){
      alert('submited!')
    }
  }
})

谢谢!

3 个答案:

答案 0 :(得分:1)

我会阻止表单上的默认值,然后将提交的逻辑移动到按钮。

&#13;
&#13;
Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    options: ["some", "thing", "another", "things"]
  },
  methods: {
    submitted() {
      console.log('submited!')
    }
  }
})
&#13;
body {
  font-family: 'Open Sans', sans-serif;
}

#app {
  max-width: 35em;
  margin: 1em auto;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="https://unpkg.com/vue-select@2.2.0/dist/vue-select.js"></script>
<div id="app">
  <h1>Vue Select</h1>
  <p>Try to add items in input using "ENTER"</p>
  <form v-on:submit.prevent="">
    <v-select multiple :options="options"></v-select>
    <button type="button" v-on:click="submitted()">Submit</button>
  </form>
</div>
&#13;
&#13;
&#13;

见这里: https://codepen.io/uidan/pen/PJjOyb

答案 1 :(得分:1)

如果您只想阻止特定组件上的按键提交表单,但希望保留所有其他默认表单行为(例如,可能包括在输入其他输入时按Enter键),则可以捕获本机组件上的按键事件:

<v-select multiple :options="options" @keypress.native.prevent=""></v-select>

答案 2 :(得分:1)

解决,完美运作。

   <div id="app">
      <h1>Vue Select</h1>
      <p>Try to add items in input using "ENTER"</p>
      <form v-on:submit.prevent="">
      <v-select multiple :value.sync="selected" :options="options"></v-select>
        <button type="submit" @click="submitedd()">Submit</button>
      </form>
    </div>


Vue.component('v-select', VueSelect.VueSelect);

new Vue({
  el: '#app',
  data() {
    return {
      selected: null,
      options: ["some", "thing", "another", "things"]
    }
  },
  methods: {
    submitedd(){
      console.log("i am here");
    }
  }
})