在下面的代码中,我试图在Polymer元素中声明一个属性,允许用户选择元素的flex-direction
,但它不起作用。有人可以提供一个有效的例子吗?
Polymer({
is: 'container-element',
properties: {
flexDirection: {
type: String,
reflectToAttribute: true,
computed: '_changeFlexDirection(dir)'
}
},
_changeFlexDirection: function(dir){
var el = document.getElementsByTagName('container-element')[0];
return el.style.flexDirection = "column";
}
});
答案 0 :(得分:1)
看起来您正在尝试实现simple observer,但是您无意中使用了计算属性。此外,使用document.getElementsByTagName()
来获取对元素自身样式的引用是不必要的(如果元素的多个实例在文档中,则会出错),因为您可以使用{{1 }}。您的代码已更正:
this.style
properties: {
flexDirection: {
type: String,
observer: '_flexDirChanged'
}
},
_flexDirChanged: function(flexDirection) {
this.style.flexDirection = flexDirection;
}

您还可以公开用户可以覆盖的CSS property。此示例的默认<head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<x-foo></x-foo>
<x-foo flex-direction="row"></x-foo>
<dom-module id="x-foo">
<template>
<style>
:host {
display: flex;
flex-direction: column;
}
</style>
<div>a</div>
<div>b</div>
<div>c</div>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-foo',
properties: {
flexDirection: {
type: String,
observer: '_flexDirChanged'
}
},
_flexDirChanged: function(flexDirection) {
this.style.flexDirection = flexDirection;
}
});
});
</script>
</dom-module>
</body>
为flex-direction
,并公开column
以覆盖--x-foo-flex-direction
中的默认值。
custom-style
// index.html
<style is="custom-style">
.row {
--x-foo-flex-direction: row;
}
</style>
<x-foo class="row"></x-foo>
// x-foo.html
<style>
:host {
display: flex;
flex-direction: var(--x-foo-flex-direction, column);
}
</style>
&#13;