我有一个下拉列表(和其他输入),只有在用户选中复选框时才需要显示。为了保持 UI 干净,它隐藏在 v-if 后面:
<input type="checkbox" id="override" name="override" v-model="override"/>
<div v-if="override">
<input type="number" name="overridePrice" v-model="overridePrice"/>
<select class="overrideReason" name="overrideReason" id="overrideReason">
<option v-for"res in override_reason" :value="res.id">{{ res.text }}</option>
</select>
</div>
我最初在观察器上设置了此设置,因为 overridePrice > 0 有效:
watch: {
overridePrice: function(val){
if(val>0){
$('.overrideReason').select2();
}
}
},
然而,无论值是 0 还是更大,都需要下拉的原因,所以我认为将其更改为监视 bool 值同样容易,但它不起作用,select2 未正确初始化,我是留下标准的 HTML 下拉列表:
watch: {
override: function(val){
if (val){
console.log("This will print");
$('.overrideReason').select2()'
}
}
},
控制台日志按预期工作,但初始化没有。 这是一个错误还是我遗漏了有关 Vue watchers/JQuery/Select2 的某些信息?
最佳答案
这可能是 .overrideReason
在 watch 函数运行时不可用。您可以使用 $nextTick
watch: {
override: function(val){
if (val){
this.$nextTick(() => {
console.log("This will print");
$('.overrideReason').select2()'
})
}
}
},
关于javascript - 使用watcher在Vue条件渲染中选择2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53586339/