首页 > 解决方案 > 如何在 web 组件中的 prop 更改后重新渲染?(Javascript香草)

问题描述

我有一个 Web 组件,可以使用时间跟踪数据呈现卡片。当我在每天/每周/每月之间切换时,会进行一次提取并且组件的属性会发生变化,但即使我可以看到组件状态内部的变化,组件也不会呈现这些变化

class TimePanel extends HTMLElement {
constructor() {
    super();
    this.attachShadow({ mode: "open" })
}

getTemplate() {
    const template = document.createElement('template');
    template.innerHTML = `
        <section class="general-panel">
        <div class="inner-card work">
            <div class="sub-panel">
            <div class="flex-container">
                <p class="card-title">${this.area}</p>
                <span class="options">
                        <img src="../../images/icon-ellipsis.svg" alt="">
                </span>
            </div>
            <div class="flex-container">
                <span class="time">${this.time}Hs</span>
                <span class="previous-date">last week - ${this.previousDate}Hs</span>
            </div>
            </div>
        </div>
    `
    return template;
}

connectedCallback() {
    this.shadowRoot.append(this.getTemplate().content.cloneNode(true))
}

static get observedAttributes() {
    return ['area','time','previous-date'];
}

attributeChangedCallback(name, old, newV) {
    if(name === 'area') {
        this.area = newV;
    }
    if(name === 'time') {
        this.time = newV;
    }
    if(name === 'previous-date') {
        this.previousDate = newV;
    }

}

}

customElements.define('time-panel', TimePanel)

标签: javascriptcomponents

解决方案


从您提供的代码看来,您似乎缺少属性的 getter 和 setter。

例如。

get area() {
  return this.getAttribute("area");
} 
set area(value) {
   this.setAttribute("area", value);
}

推荐阅读