gpt4 book ai didi

javascript - 元素未更新 html Polymer V3 上的值

转载 作者:行者123 更新时间:2023-12-01 00:39:34 27 4
gpt4 key购买 nike

在使用 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
}
}

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

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

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

关于javascript - 元素未更新 html Polymer V3 上的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57819724/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com