元素未更新 html 聚合物 V3 上的值



我想在使用AddItem()方法在子组件中添加新项目后更新父组件中的 todoList。第一次不会添加任何内容。 如果我添加"进行测试"不会得到渲染,那么如果我添加"洗澡"不会得到渲染,但现在"进行测试"会。然后,如果我添加"泄漏",则会渲染"洗澡"。

父组件

firstUpdated(changedProperties) {
this.addEventListener('addItem', e => {
this.todoList = e.detail.todoList;
});
}
render() {
return html`
<p>Todo App</p>
<add-item></add-item>//Child item that triggers the add
<list-items todoList=${JSON.stringify(this.todoList)}></list-items>
`;
}

子组件

AddItem() {
if (this.todoItem.length > 0) {
let storedLocalList = JSON.parse(localStorage.getItem('todo-list'));
storedLocalList = storedLocalList === null ? [] : storedLocalList;
const todoList = [
...storedLocalList,
{
id: this.uuidGenerator(),
item: this.todoItem,
done: false
}
];
localStorage.setItem('todo-list', JSON.stringify(todoList));
this.dispatchEvent(
new CustomEvent('addItem', {
bubbles: true,
composed: true,
detail: { todoList: storedLocalList }
})
);
this.todoItem = '';
}
}
render() {
return html`
<div>
<input .value=${this.todoItem} @keyup=${this.inputKeyup} />
<button @click="${this.AddItem}">Add Item</button>
</div>
`;
}

您需要为todoItem设置properties

static get properties() {
return { 
todoItem: {
type: Array, 
Observer: '_itemsUpdated' 
}
}
constructor(){ 
this.todoItem = [] 
}
_itemsUpdated(newValue,oldValue){
if(newValue){
-- write your code here.. no event listeners required
}
}

在上面的代码中,我们需要在constructor中初始化空数组。

Observer观察数组和触发器的变化itemsUpdated带有oldValue和NewValue的函数。在该函数中,您可以放置逻辑。

根据我的假设,不需要事件侦听器

发现我的错误。我正在传递细节:{ todoList : storedLocalList } 这是没有更新值的旧数组。

AddItem() {
if (this.todoItem.length > 0) {
let storedLocalList = JSON.parse(localStorage.getItem('todo-list'));
storedLocalList = storedLocalList === null ? [] : storedLocalList;
const todoList = [
...storedLocalList,
{
id: this.uuidGenerator(),
item: this.todoItem,
done: false
}
];
localStorage.setItem('todo-list', JSON.stringify(todoList));
this.dispatchEvent(
new CustomEvent('addItem', {
bubbles: true,
composed: true,
detail: { todoList: todoList }
})
);
this.todoItem = '';
}
}

最新更新