LWC在@wire的DIV上执行querySelector

问题描述

在全球行动中,我有一个LWC作为快速行动。 执行wire方法,然后在数据块中执行另一种对div执行querySelector的方法。 第一次打开快速动作LWC时,querySelector成功执行。 当我关闭快速操作窗口并再次打开它时,querySelector为null。 只有刷新后,querySelector才能再次成功执行。

<div data-parent-id="parent-div-id" class={parentClass} style={parentStyle}>

@wire(isUser)
wiredisUser({data,error}) {
    if (data) {
        this.isUser = data;
        this.setCssClass();
    } else if (error) {
        console.log('Error wire:',error.body.message);
    }
} 

setCssClass() {
    let element = this.template.querySelector('[data-parent-id="parent-div-id"]');
    console.log('element:',element); // not null the first time,but null the second time
    if (element && this.isUser) {
        let height = element.getBoundingClientRect().height;
        let width = element.getBoundingClientRect().width;
        this.parentClass = 'slds-p-around_large slds-scrollable_y';
        this.parentStyle = 'height:' + height + 'px; width:' + width + 'px;';
    }
} 

解决方法

第一次打开组件时,会从Server拉取数据,在此期间组件已经渲染完成,调用setCssClass(),querySelector就可以正常工作了。由于方法是有线的,因此响应会缓存在浏览器上。

下次打开组件时,数据会从缓存中提取,这会很快/在组件呈现之前发生,因此 querySelector 不返回任何内容。

在这种情况下,您可能想要更改方法。