如何使用具有 Object-type 属性的 Lit-element?我认为定义 myelement 有效:
static get properties() {
return {
whales:Object
}
}
constructor() {
super();
this.whales={"nb":0};
}
html,这也有效:
<my-element id="mytest" whales='{"nb":2}'></my-element>
但我无法让 setAttribute 工作:
myElement.setAttribute("whales", {"nb":4});
编辑:谢谢你,你的回答帮助我解决了我的问题。如果有人想知道,这是完整的工作示例。但是,还有一件事我无法工作:如果值是对象(对象作为字符串处理),我不知道如何以声明方式为属性赋予初始值。
索引.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lit-html test</title>
</head>
<body>
<script type="module" src="./components/my-e.js"></script>
<button id="reset" onclick="reset()">reset</button>
<p>1 works: <my-e id="mytest"></my-e></p>
<p>2 doesn't work: <my-e id="mytest2" person='{"name":"Joe", "age":32}'></my-e></p>
<script src="main.js"></script>
</body>
</html>
主.js:
function updatePerson(e) {
var myE = e.target;
myE.person = e.detail;
myE._requestRender();
}
function reset() {
var p = { "name": "Jack", "age": 20 };
var myE = document.getElementById('mytest');
myE.person = p;
myE._requestRender();
myE = document.getElementById('mytest2');
myE.person = p;
myE._requestRender();
}
document.getElementById('mytest').addEventListener('person', updatePerson);
document.getElementById('mytest2').addEventListener('person', updatePerson);
我的-e.js:
import { LitElement, html } from './lit-element.js';
class MyE extends LitElement {
static get properties() {
return {
person: Object
}
}
constructor() {
super();
this.person = { "name": "Paul", "age": 40 };
this.addEventListener('click', async (e) => {
await this.renderComplete;
var p = {};
p.name = this.person.name + ", a";
p.age = this.person.age + 1;
this.dispatchEvent(new CustomEvent('person', { detail: p }))
});
}
_render({ person }) {
return html`
<p> Name: ${person.name}</p>
<p>Age: ${person.age}</p>
`;
}
}
customElements.define('my-e', MyE);