简体   繁体   中英

How to re-render after prop change in a web-component? (Javascript Vanilla)

I have a web component that render a card with time-tracking data. When I switch between daily/weekly/monthly a fetch is made and the attributes of the component change, but even I can watch the changes inside the component state, the component doesn't render these changes

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)

From the code you provided it seems that you are missing a getter and a setter for the attributes.

eg.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM