gpt4 book ai didi

javascript - 使用属性或插槽将数据传递给子元素

转载 作者:行者123 更新时间:2023-11-29 20:48:17 26 4
gpt4 key购买 nike

我想知道将某些值从父组件传递到子组件并显示该值的最佳方式是什么,因为我尝试过使用属性和插槽传递值,并且这两种方式都有效。属性:我有一个移动列表,并在父组件中使用 lit-html 中的 repeat(和方法 html 来呈现),以便创建 n 个子组件并给出值在它们的属性中。

//father component
render(){
return html`
${repeat(movements, movement => movement.id, (movement, index)=> html`
<movement
.id=${movement.id} .description=${movement.description} .amount=${movement.amount} .balance=${movement.balance}>
</movement>
<hr>
`)}
`
}

//child component
render(){
return html`
<dt>${this.id}</dt>
<dl>${this.description}</dl>
<dl>${this.amount}</dl>
<dl>${this.balance}</dl>
`;
}

插槽:我有一个移动列表,并在父组件中使用 lit-html 中的 repeat(和方法 html 进行渲染)以创建 n 个子组件给出在子组件中声明的插槽中的值

//child component
render(){
return html`
<dd>
<slot name="id"></slot>
<slot name="description"></slot>
<slot name="amount"></slot>
<slot name="balance"></slot>
</dd>
`;
}

//father component
render(){
return html`
${repeat(movements, movement=>movement.id, (movement, index)=>html`
<movement>
<dt slot="id"> ${movement.id} </dt>
<dl slot="description"> ${movement.description} </dl>
<dl slot="amount"> ${movement.amount} </dl>
<dl slot="balance"> ${movement.balance} </dl>
</movement>
`)}
`;
}

哪种方法最好?我什么时候必须使用一个和另一个?

最佳答案

下面是一个使用 LitElement 传递对象属性的例子:

DEMO

import { LitElement, html } from '@polymer/lit-element'; 

class MyElement extends LitElement {

static get properties() { return {
movements: {
type:Object
}
}
}

constructor(){
super();
// Initialize property here.
this.movements = [{id:"123", amount:40000, description:"Bu yuzyilin en buyuk lideri Atatürk tür", balance:20000},{id:"123", amount:40000, description:"Tosun was here ! :) ", balance:20000},{id:"123", amount:40000, description:"Ne Mutlu Diyene, Buraarda ırkçı olmayahh :)) ", balance:20000}];
}

//father component
render(){
return html`
${this.movements.map(movement => html`<movement-list .id=${movement.id} .description=${movement.description} .amount=${movement.amount} .balance=${movement.balance}></movement-list>`)}

`;
}
}

class MovementList extends LitElement {

static get properties() { return {
id: {type:String},
description: {type:String},
amount: {type:Number},
balance: {type:Number}
}
}
//child component
render(){
return html`
<dt>${this.id}</dt>
<dl>${this.description}</dl>
<dl>${this.amount}</dl>
<dl>${this.balance}</dl>

`;
}

}
customElements.define('my-element', MyElement);
customElements.define('movement-list', MovementList);

关于javascript - 使用属性或插槽将数据传递给子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317709/

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