我在聚合物2.x中遇到了一个简单的问题。我不知道如何从另一个元素类中正确设置我的自定义元素属性的值。如何在Polymer 2.x中设置属性值?
我的代码:
<dom-module id="cookbook-wall">
<template>
<style>
// my styling
</style>
<div class="wall">
<template is="dom-repeat" items="[[_getRecipesList()]]">
<cookbook-recipe-card name="recipe-card"></cookbook-recipe-card>
</template>
</div>
</template>
<script>
class CookbookWall extends Polymer.Element {
static get is() {
return 'cookbook-wall';
}
static get properties() {
// this property is unused now, I tried to set it dynamically from
// method below but it also failed
return {
recipes: Array
}
}
_getRecipesList() {
var test = new CookbookRecipeCard();
test.setData("This is test title", "This is test content");
return [test, test, test];
}
}
window.customElements.define(CookbookWall.is, CookbookWall);
</script>
和
<dom-module id="cookbook-recipe-card">
<template>
<style include="shared-styles">
// my styling
</style>
<div class="card">
<div id="titleContent">{{title}}</div>
<div class="my-block">
<div class="contentCaption">Treść przepisu:</div>
<div class="content">{{content}}</div>
</div>
</div>
</template>
<script>
class CookbookRecipeCard extends Polymer.Element {
static get is() {
return 'cookbook-recipe-card';
}
static get properties() {
return {
myName: String,
myContent: String
}
}
setData(myTitle, myContent) {
this.myTitle = myTitle;
this.myContent = myContent;
}
}
window.customElements.define(CookbookRecipeCard.is, CookbookRecipeCard);
</script>
正如你看到我想要做做某事,如:setData(myTitle, myContent)
从另一个要素类,但它不没有工作。有没有什么办法可以在Polymer中用面向对象的语言实现类似于传统setter的结果?
感谢您的帮助!
EDIT(我的解决方案):
我删除了自定义的卡构件,只是使用普通纸卡:
<dom-module id="cookbook-wall">
<template>
<style>...</style>
<div class="wall">
<template id="cardSet" is="dom-repeat" items="[[_getArray()]]" as="card">
<paper-card id="myCard">
<div class="card">
<div id="titleContent">[[card.title]]</div>
<div class="my-block">
<div class="contentCaption">Treść przepisu:</div>
<div class="content">[[card.text]]</div>
</div>
</div>
</paper-card>
</template>
</div>
</template>
<script>
class CookbookWall extends Polymer.Element {
static get is() {
return 'cookbook-wall';
}
_getArray() {
// example usage
return [{'title': 'Title 1', 'text': 'Description 1'},
{'title': 'Title 2', 'text': 'Description 2'},
{'title': 'Title 3', 'text': 'Description 3'}];
}
}
window.customElements.define(CookbookWall.is, CookbookWall);
</script>
它的工作,但传递自定义卡属性仍然有一些问题(他们是由我的应用程序结构引起的)。我编辑了原文,并添加了我的解决方案。谢谢你的帮助。 – Custodian