我有一个LitElement,它代表多个文件的文件上传。这使用一个表示每个文件的子组件。
我很难找到使用LitElements将更改传播到子组件的最佳实践示例,因为它似乎与聚合物3有很大的不同
下面是我正在尝试的一个简单的例子:
import './uploadFile.js';
class Upload extends LitElement {
...
static get properties() { return { files: Object } }
_render({files}) {
return html`
<input type="file" multiple onchange="...">
${this.renderFiles(files)}`
}
renderFiles(files) {
const filesTemplate = [];
for (var i = 0; i < files.length; i++) {
filesTemplate.push(html`
<upload-file file="${files[i]}"></upload-file>
`);
}
return filesTemplate;
}
}当我更新一个文件的状态时,上传组件会重新呈现,但是上传文件组件不会。
我在这里做错什么了?目前还没有LitElement使用的例子。
提亚
发布于 2018-09-13 03:29:38
最佳实践是“属性向下,事件向上”;这意味着父元素应该通过将属性绑定到其子元素来与子元素共享数据,而子元素应该通过使用事件细节中的相关数据引发事件来与父元素共享数据。
我不能评论您做错了什么,因为我看不到您是如何更新文件的状态或子元素的实现的。
需要注意的一件事是,由于脏检查,listed只能观察到您在properties getter中列出的顶级属性的更改,而不是它们的子属性。
有点像
this.myObj = Object.assign({}, this.myObj, {thing: 'stuff'});将触发对对象及其要呈现的子属性的更改,而
this.myObj.thing='stuff';不会的。
要获得子属性更改以触发重呈现,您需要使用requestRender()请求一个或克隆整个对象。
下面是一些示例代码,显示了一个基本的“属性向下,事件向上”模型:
警告:发光元素仍处于预发布状态,语法将发生变化。
parent-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);child-element.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);希望这能有所帮助。
https://stackoverflow.com/questions/52301757
复制相似问题