最佳实践是“属性下降,事件上升”;这意味着父元素应该通过将属性绑定到子元素来与子元素共享数据,子元素应该通过在事件的细节中引发带有相关数据的事件来与父元素共享数据。
我无法评论您做错了什么,因为我看不到您如何更新文件的状态或子元素的实现。
需要注意的一件事是,由于脏检查,lit-element 只能观察到您在 getter 中列出的顶级属性的更改properties
,而不是它们的子属性。
就像是
this.myObj = Object.assign({}, this.myObj, {thing: 'stuff'});
将触发对对象及其子属性的更改以进行渲染,而
this.myObj.thing='stuff';
将不会。
要获得子属性更改以触发重新渲染,您需要请求一个requestRender()
或克隆整个对象。
下面是一些示例代码,显示了一个基本的“属性关闭,事件向上”模型:
警告: lit-element 仍然是预发布的,语法将会改变。
父元素.js
import { LitElement, html} from '@polymer/lit-element';
import './child-element.js';
class ParentElement extends LitElement {
static get properties(){
return {
myArray: Array
};
}
constructor(){
super();
this.myArray = [
{ val: 0, done: false },
{ val: 1, done: false },
{ val: 2, done: false },
{ val: 3, done: false }
];
}
_render({myArray}){
return html`
${myArray.map((i, index) => {
return html`
<child-element
on-did-thing="${(e) => this.childDidThing(index, i.val)}"
val="${i.val}"
done="${i.done}">
</child-element>
`})}
`;
}
childDidThing(index, val){
this.myArray[index].done=true;
/**
* Mutating a complex property (i.e changing one of its items or
* sub-properties) does not trigger a re-render, so we must
* request one:
*/
this.requestRender();
/**
* Alternative way to update a complex property and make
* sure lit-element observes the change is to make sure you
* never mutate (change sub-properties of) arrays and objects.
* Instead, rewrite the whole property using Object.assign.
*
* For an array, this could be (using ES6 object syntax):
*
* this.myArray =
* Object.assign([], [...this.myArray], {
* [index]: { val: val, done: true }
* });
*
*/
}
}
customElements.define('parent-element', ParentElement);
子元素.js
import { LitElement, html} from '@polymer/lit-element';
class ChildElement extends LitElement {
static get properties(){
return {
val: Number,
done: Boolean
};
}
_render({val, done}){
return html`
<div>
Value: ${val} Done: ${done}
<button on-click="${(e) => this.didThing(e)}">do thing</button>
</div>
`;
}
didThing(e){
var event = new CustomEvent('did-thing', { detail: { stuff: 'stuff'} });
this.dispatchEvent(event);
}
}
customElements.define('child-element', ChildElement);
希望有帮助。