现在,当 rating attribute 变化时更新视图;这类似于当你设置 <input value="newValue"> 时输入框更新其视图。幸运的是,Web Component 生命周期包含了 attributeChangedCallback。通过添加以下代码来更新评分:
static get observedAttributes() { return ['rating'];}
attributeChangedCallback(attributeName: string, _oldValue: string, newValue: string) { if (attributeName === 'rating') { const newRating = Number(newValue);
this.rating = newRating; }} static get observedAttributes() { return ['rating'];}
attributeChangedCallback(attributeName, _oldValue, newValue) { if (attributeName === 'rating') { const newRating = Number(newValue);
this.rating = newRating; }} 为了让 attributeChangedCallback 触发,你必须为 RatingElement.observedAttributes 设置一个静态 getter,声明哪些 attribute 应该被观察变化。然后你可以在 DOM 中声明式地设置 rating attribute。试试看:
<rating-element rating="5"></rating-element> 评分现在应该声明式地更新了!