我从Polymer 3开始,现在遇到无法解决的问题。
我有一个自定义元素,将显示一张纸牌;它唯一的属性是带有其西装和编号的对象。元素或多或少是这样的:
import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
class CardElement extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
`;
}
static get properties() {
return {
card: {
type: Object,
value: () => {
return {
suit: 'hearts',
figure: 'king'
}
}
},
};
}
ready() {
super.ready();
console.log(this.card.figure);
}
}
window.customElements.define('card-element', CardElement);
下一步,我要检查所有内容是否正常运行以及HTML文件。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>card-element demo</title>
<script src="../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module">
import '@polymer/iron-demo-helpers/demo-pages-shared-styles';
import '@polymer/iron-demo-helpers/demo-snippet';
</script>
<script type="module" src="../card-element.js"></script>
<custom-style>
<style is="custom-style" include="demo-pages-shared-styles">
</style>
</custom-style>
</head>
<body>
<div class="vertical-section-container centered">
<h3>Basic card-element demo</h3>
<demo-snippet>
<template>
<card-element card='{"suit" "hearts", "figure" "1"}'></card-element>
</template>
</demo-snippet>
</div>
</body>
</html>
就绪方法中的Console.log显示数据已绑定,但是每当我尝试传递从函数返回的json数据时,console.log都显示“未定义”。
<body>
<div class="vertical-section-container centered">
<h3>Basic card-element demo</h3>
<demo-snippet>
<template>
<card-element card="{{_getCard}}"></card-element>
</template>
</demo-snippet>
</div>
<script>
function _getCard() {
return JSON.stringify({
"suit": "clubs",
"figure":"1"
});
}
</script>
</body>
我检查了加载返回到变量中的数据,并将该变量绑定到自定义元素,但仍然无法正常工作。
如何将数据传递给自定义元素?
感谢您的回答。
答案 0 :(得分:0)
尝试一下:
<script>
function _getCard() {
let data = {
"suit": "clubs",
"figure":"1"
};
return data;
}
</script>