【问题标题】:"shadowRoot.querySelector" not working with lit-element in Web Components“shadowRoot.querySelector”不适用于 Web 组件中的 lit-element
【发布时间】:2021-03-08 16:20:21
【问题描述】:

好的,所以我在这里看到了一些与我类似的问题,但没有一个解决方案对我有用,所以我认为最好更具体地描述我的问题。

我正在使用 web 组件,起初我没有使用 lit 元素,当时this.shadowRoot.querySelector('button') 工作得很好,但现在我使用的是 lit 元素,这个选择器总是返回 null,这是我的代码:

static get styles(){
    return css`
        button{
            color: #737373;
            padding: 15px 30px;
            font-size: 16px;
        }
        .primary{
            border-radius: 25px;
            border: 1px solid;
            color: #4386ff;
            transition: 0.3s;
        }
        .disabled {
            pointer-events: none;
            color: #cacaca;
            background-color: #fff;
        }
    `;
}

static get properties(){
    return{
        type: { type: String },
        text: { type: String},
        fullSize: { type: Boolean},
        disabled: { type: Boolean}
    };
}
constructor() {
    super();
    this.type = "primary";
    this.text = "Seguir";
    this.disabled = false;
    this.fullSize = false;
    this.el = this.shadowRoot.querySelector('button');

    if (this.hasAttribute('disabled'))  {
        this.el.classList.add('disabled');
    }
}

render () {
    return html`
    <button class="${this.type}" 
    ?fullSize="${this.fullSize}"
    ?disabled="${this.disabled}"
    >${this.text}</button>
`;
}

}

这样this.shadowRoot.querySelector('button')always 返回null! 我应该使用一些生命周期方法来使其工作吗?我试过updated,但也没有用。

我的 HTML 组件是这样的:

<default-button type="secondary" text="Salvar" fullSize></default-button>

【问题讨论】:

  • 可以在不使用 Lit 时显示代码吗? Lit 是标准技术之上的sugar,所以如果您的标准代码有效...
  • 因为元素还在构建中,所以按钮还不存在。在firstUpdated(changedProperties) { ... } 方法中调用this.el =...if 语句。
  • 我阅读了一些关于生命周期的其他内容,现在我了解了当我第一次尝试调用它时仍在构建的元素,现在使用它工作的第一个更新方法!谢谢!

标签: javascript web-component lit-element


【解决方案1】:

好的,我阅读了一些关于生命周期的其他内容,现在我了解了当我第一次尝试调用它时仍在构建的元素,现在使用 firstUpdated() 方法它可以工作!谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多