javascript - 如何在 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)
解决方案
从您提供的代码看来,您似乎缺少属性的 getter 和 setter。
例如。
get area() {
return this.getAttribute("area");
}
set area(value) {
this.setAttribute("area", value);
}
推荐阅读
- webrtc - Webrtc 连接过度与中继候选者发生奇怪的行为
- c# - 为什么“不等于”和“或”在 C# 中不起作用(检查数字是否为二进制)?
- ios - 今日扩展 - 无法加载 [Swift]
- react-native - 世博会开始显示未终止的字符子句错误
- python - 使用每个切片的百分位数过滤多维 numpy 数组
- c# - 有没有办法在 c# 中强制引用另一个 ref 类型?
- resharper - Resharper 命令行工具抛出异常
- computer-science - 图灵机用于平衡括号
- bash - Azure DevOps 中的“bash exited with code 1”中的 Cypress 测试退出失败
- laravel - Laravel Voyager 图表未显示在仪表板中