获取vue-select值不起作用

Joh*_* H. 2 javascript vue.js vue-component vuejs2 vue-select

我正在尝试从vue-select中获取选定的值,但是已经使用了所有方法并搜索了帮助,但是这可以正常工作,在页面加载时也会触发警报

Vue.component('v-select', VueSelect.VueSelect)
new Vue({
  el: '#app',
  data: {
    options: [      
      {id: 1, label: 'foo'},
      {id: 3, label: 'bar'},
      {id: 2, label: 'baz'},
    ],
    selected: '',
  },
  methods: {
    runme: function() {
      alert(this.selected);
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
body {
  font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif;
}

h1 {
  font-size: 26px;
  font-weight: 600;
  color: #2c3e5099;
  text-rendering: optimizelegibility;
  -moz-osx-font-smoothing: grayscale;
  -moz-text-size-adjust: none;
}

#app {
  max-width: 30em;
  margin: 1em auto;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://vuejs.org/js/vue.js"></script>
<script src="https://unpkg.com/vue-select@2.4.0/dist/vue-select.js"></script>
<div id="app">
  <h1>Vue Select - Using v-model</h1>
  <v-select v-model="selected" :on-change="runme" :options="options"></v-select>  
</div>
Run Code Online (Sandbox Code Playgroud)

小智 6

vue-select author here. The on-change callback will be deprecated in v2.5.0 and removed in v2.6.0. Here's the prop from the v2.4.0 source:

/**
 * An optional callback function that is called  
 * each time the selected value(s) change.
 *
 * @type {Function}
 * @param {Object || String} val
 */
onChange: {
  type: Function,
  default: function (val) {
    this.$emit('input', val)
  }
}
Run Code Online (Sandbox Code Playgroud)

As Bob Dust explained, the key here is that onChange calls this.$emit('input',val), which is what Vue hooks into to provide the v-model syntax. If the event is not emitted, Vue is unaware of the change.

如果您需要v-model并且还希望随时更改值,则监听@input事件是最佳选择:

<v-select v-model="selected" @input="runme" :options="options"></v-select>
Run Code Online (Sandbox Code Playgroud)