我正在通过Polymer 2.0玩Web Components .
我想写的最终HTML看起来像这样:
<card size="small">
<card-header>
// Markup
</card-header>
<card-body>
// Markup
</card-body>
<card-footer>
// Markup
</card-footer>
</card>
如您所见,我将大小传递给顶级组件 . 我打算听这些卡片的宽度,并减少页眉,主体和页脚上的填充,当它们变得更小,基本上是响应元素 .
我无法弄清楚如何做的是获取size的属性值传递给 card-header
, card-body
和 card-footer
聚合物声明 .
这里's how I' m定义 card
:
<link rel="import" href="card-header.html">
<dom-module id="card">
<template>
<style>
// Style things
</style>
<slot></slot>
</template>
<script>
Polymer({
is: 'card',
properties: {
size: {
type: String,
value: "medium",
observer: '_observeSize'
},
},
_observeSize: function () {
const sizes = {
tiny: "1em",
small: "2em",
medium: "3em",
large: "6em"
};
if (this.size == "tiny") {
this.customStyle['--padding-x'] = sizes.tiny;
this.customStyle['--padding-y'] = sizes.tiny;
} else if (this.size == "small") {
this.customStyle['--padding-x'] = sizes.small;
this.customStyle['--padding-y'] = sizes.small;
} else if (this.size == "medium") {
this.customStyle['--padding-x'] = sizes.medium;
this.customStyle['--padding-y'] = sizes.medium;
} else if (this.size == "large") {
this.customStyle['--padding-x'] = sizes.large;
this.customStyle['--padding-y'] = sizes.large;
} else {
this.customStyle['--padding-x'] = sizes.medium;
this.customStyle['--padding-y'] = sizes.medium;
}
this.updateStyles();
},
_responsiveObserver: function () {
// Update this.size based on width of this element.
}
});
</script>
</dom-module>
在这里's how I' m定义 card-header
<dom-module id="card-header">
<template>
<style>
// Style
</style>
<slot></slot>
</template>
<script>
Polymer({
is: 'card-header',
properties: {
size: {
type: String,
}
},
ready: function () {
console.log(this.size);
// console.log(hostValue::size); ???? something like this ????
}
});
</script>
</dom-module>
TL; DR:如何获取父节点的属性值,或者将值传递给特定子节点( card-header
或 card-body
或 card-footer
)而不使用Polymer更新DOM中的属性?
1 回答
解
有几种方法可以解决这个问题,但我意识到我在
<slot></slot>
中放置了我需要的东西,所以我可以在卡级别执行填充逻辑然后处理CSS变量 .