【问题标题】:Setting v-select value programmatically does not fire @change in vuetify以编程方式设置 v-select 值不会在 vuetify 中触发 @change
【发布时间】:2018-11-20 18:04:03
【问题描述】:

我正在尝试以编程方式设置 v-select 值,但是关联的 @change 事件不会触发。如果我手动选择该选项,事件会按预期触发。

模板:

<div id="app">
<v-app dark>
  <v-select 
    v-model="currentItem" 
    :items="items"
    @change="itemChanged"
  />
</v-app>
</div>

JS:

Vue.use(Vuetify);

var vm = new Vue({
    el: "#app",
  methods: {
    itemChanged(item) {
        console.log('item changed',item);
    }
  },
  data: {
    currentItem: '',
    items: [
        { text: "Name", value: 'name' },
      { text: "Number", value: 'number' },
      { text: "Inputs", value: 'inputs' }
    ]
  },
  mounted() {
    setTimeout(() => {
        this.currentItem = 'inputs';
    }, 2000);
  }
});

jsfiddle is here

在以编程方式设置值时,除了手动调用函数之外,还有其他解决方案吗?

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    change 事件是这样定义的,所以它是emitted when the input is changed by user interaction (see the event documentation)。如果要监控所有更改,可以使用input 事件:

    <v-select 
      v-model="currentItem" 
      :items="items"
      @input="itemChanged"/>
    

    https://jsfiddle.net/0qbomzta/


    或添加一个观察者观察currentItem:

    <div id="app">
    <v-app dark>
      <v-select 
        v-model="currentItem" 
        :items="items"/>
    </v-app>
    </div>
    

    在Vue 实例中,添加:

    watch: {
      currentItem (newVal) {
        console.log('item changed', newVal);
      }
    },
    

    https://jsfiddle.net/w5voub3h/

    【讨论】:

    • 是的,我最终使用了观察者。这不是最优雅的解决方案,但它有效
    • 它对我有用,即使我有不同的问题。我在 v-for 中几乎没有 v-select。当我添加提供的侦听器时:on-change.即使我只更改其中一个,它也会在每个 v-select 模型上触​​发
    猜你喜欢
    • 2020-07-20
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2020-07-13
    • 1970-01-01
    • 2021-08-09
    • 2021-05-25
    相关资源
    最近更新 更多