获取 vue-select 值无效

get vue-select value not working

我正在尝试从 vue-select 中获取 selected 值,但是我已经使用了所有方法并搜索了帮助,但这是否可行,我也有在页面时触发警报负载

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);
    }
  }
})
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;
}
<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>

是你在 change 事件上的处理程序抑制了 input 事件的发出(实际上在 v-model 的两种绑定方式中发挥作用)。你只需要听 input 代替:

<v-select v-model="selected" @input="runme" :options="options"></v-select>

这里有一些事情,第一个问题是 runme 方法。通过使用 function,您正在更改 this 的上下文。要访问数据 属性 你应该使用 es6 箭头语法:

  methods: {
    runme: () => {
      alert(this.selected);
    }
  }

其次,您甚至不需要 selected,只需将值作为参数传递给 runme

这里是working fiddle.

更新了您的代码段

Vue.component('v-select', VueSelect.VueSelect)
new Vue({
  el: '#app',
  data() {
    return {
      options: [{
        value: 1,
        label: 'foo'
      }, {
        value: 3,
        label: 'bar'
      }, {
        value: 2,
        label: 'baz'
      }, ],
    }
  },
  methods: {
    runme: selected => {
      alert(`label: ${selected.label} value: ${selected.value}`);
    }
  }
})
<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 :on-change="runme" :options="options"></v-select>
</div>

vue-select作者在这里。 on-change 回调将在 v2.5.0 中弃用并在 v2.6.0 中移除。这是来自 v2.4.0 来源的道具:

/**
 * 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)
  }
}

正如 Bob Dust 所解释的,这里的关键是 onChange 调用 this.$emit('input',val),这是 Vue 挂钩以提供 v-model 语法的内容。如果事件没有发出,Vue 不知道变化。

如果您需要 v-model 并且还想在值发生变化时随时采取行动,监听 @input 事件是最佳选择:

<v-select v-model="selected" @input="runme" :options="options"></v-select>