首页 > 解决方案 > jQuery 需要 0ms 的超时时间才能在 vue.js 组件中查找元素

问题描述

我在 vue 组件中使用 Jquery。我需要#container通过 jquery 分配另一个函数。仅当#container类型不是默认值时才存在。这是一个真正的性能密集型功能,所以我真的只希望它在需要时分配它。它的工作时间timeout为 0ms。

但是有更好/更清洁的方法吗?

Vue.component( 'component', {
    data: function() {
        return {
            typeOpt: "default"
        }
    },
    watch: {
        typeOpt: function( newVal ) {
            if( newVal !== "default" )
            {
                setTimeout(function () { //When I remove this it will not update the e.g. background color
                    $('#container').css( "background", "red" );
                }, 0);
            }
        }
    },
    template: `
        <div class='component'>
            <select v-on:change="changeType">
                <option :selected="typeOpt === 'default'" value="default">Default</option>
                <option :selected="typeOpt === 'type1'" value="type1">Type1</option>
            </select>

            <div class='mainContainer'>
                <div v-if="typeOpt == 'default'">default</div>
                <div v-if="typeOpt == 'type1'">
                    <div id='container'>content 123 ABC</div>
                </div>
            </div>
        </div>
    `,
    methods: {
        changeType() {
            this.typeOpt = $('select').val();
        }
    }
});

标签: javascriptjqueryvue.js

解决方案


推荐阅读