【问题标题】:Select2 in Vue conditional rendering using watcherVue条件渲染中Select2使用watcher
【发布时间】:2019-05-04 07:25:37
【问题描述】:

我有一个下拉菜单(和其他输入),只有在用户选中复选框时才需要显示。为了保持 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>

我最初在 watcher 上设置了这个设置,因为 overridePrice > 0 有效:

watch: {
    overridePrice: function(val){
        if(val>0){
            $('.overrideReason').select2();
        }
    }
},

但是,无论值是 0 还是更大,都需要下拉的原因,所以我认为将其更改为监视布尔值同样容易,但它不起作用,select2 没有正确初始化,我留下标准的 HTML 下拉菜单:

watch: {
    override: function(val){
        if (val){
            console.log("This will print");
            $('.overrideReason').select2()'
        }
    }
},

控制台日志按预期工作,但初始化没有。 这是一个错误还是我错过了关于 Vue watchers/JQuery/Select2 的一些东西?

【问题讨论】:

    标签: javascript jquery vue.js jquery-select2


    【解决方案1】:

    这可能是.overrideReason 在手表功能运行时不可用。你可以使用$nextTick

    watch: {
        override: function(val){
            if (val){
                this.$nextTick(() => {
                  console.log("This will print");
                  $('.overrideReason').select2()'
                })
            }
        }
    },
    

    【讨论】:

    • 非常感谢,没想到还要等v-if完成渲染。
    猜你喜欢
    • 2016-12-16
    • 2021-04-09
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2022-01-18
    • 2021-11-14
    相关资源
    最近更新 更多