我在我的应用程序中使用vue-select,并试图在首次将默认值加载到vue-select输入时防止事件处理程序触发。
组件如下所示:
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
@input="saveProduct"
@search="onAccessorySearch">
<template slot="option" slot-scope="option">
<h4>{{ option.name }}</h4>
<h5>{{ option.sku }}</h5>
</template>
</v-select>如您所见,当用户更改此多选择中的值时,我希望保存该产品。它很好,但有一个问题。
select的值绑定到product.recommended_accessories数据。在应用程序的其他地方,一个产品从服务器上加载,其中包括一个recommended_accessories属性。加载产品会触发saveProduct被调用,因为vue-select设置了输入的预选选项,这显然会触发@input事件。
不管怎么说,这附近有吗?也许我在这里犯了某种设计错误。或者,我应该使用一个钩子来绑定事件处理程序,或者设置某种标志,指示产品正在加载过程中,并且不应该保存产品。
我只是想避免在产品无缘无故装完后立即保存。
发布于 2018-04-20 20:31:51
现在,我只是跟踪一个accessoryEventCount变量,该变量在加载产品时被初始化为0。然后,在对v-select accessoryEventCount > 0事件调用saveProduct之前,我要确保使用input。
这是可行的,但我仍然想知道是否有一个更优雅的解决方案。
更新
看来Vue.nextTick就是我要找的。在代码中设置产品值之前,我设置了一个标志this.isSettingProduct = true。然后设置产品,并调用Vue.nextTick(() => { this.isSettingProduct = false });。
现在,如果this.isSettingProduct == true的话,我可以避免保存产品。使用Vue.nextTick确保在异步数据更新完成之前不会将标志设置为false。
发布于 2018-04-20 22:12:55
看起来您应该绑定prop=onChange,尽管@input看起来仍然有效(请检查选择github: line# 544)。
下面是我的解决方案,在加载您的产品之前,将onChange与function () {}绑定,加载后将其绑定到您喜欢的函数中。
Vue.component('v-select', VueSelect.VueSelect)
app = new Vue({
el: "#app",
data: {
accessoryOptions: [
{'name':'a1', 'sku':'a2'},
{'name':'b1', 'sku':'b2'},
{'name':'c1', 'sku':'c2'}
],
product: {
recommended_accessories: []
},
saveProduct: function (){}
},
methods: {
onAccessorySearch: function () {
console.log('emit input')
},
loadProduct: function () {
this.product.recommended_accessories = ['a1', 'b1'] // simulate get data from the server
setTimeout( () => {
this.saveProduct = (value) => {
console.log('emit input', this.product.recommended_accessories)
}
}, 400)
}
}
})#app {
width: 400px;
}<script src="https://unpkg.com/vue@latest"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<div id="app">
<button @click="loadProduct()">Click Me!</button>
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
:on-change="saveProduct"
@search="onAccessorySearch">
<template slot="option" slot-scope="option">
<span>{{ option.name }}</span>
<span>{{ option.sku }}</span>
</template>
</v-select>
</div>
https://stackoverflow.com/questions/49949054
复制相似问题