【发布时间】:2021-11-07 01:54:12
【问题描述】:
我有一个 html 模板存储在一个变量中:
const myTemplate = html`
<my-component>
</my-component>
`
我想给myTemplate添加一个属性。
类似
myTemplate.foo = "bar"
但这引用了模板而不是元素;如何隔离元素来修改它?
【问题讨论】:
标签: javascript html lit
我有一个 html 模板存储在一个变量中:
const myTemplate = html`
<my-component>
</my-component>
`
我想给myTemplate添加一个属性。
类似
myTemplate.foo = "bar"
但这引用了模板而不是元素;如何隔离元素来修改它?
【问题讨论】:
标签: javascript html lit
对于这种情况,您通常会使用返回模板的函数。
const myTemplate = (props) => {
return html`<my-component foo=${props.foo} .bar=${props.bar}></mycomponent>`;
};
const instance = myTemplate({foo: 'some value', bar: 3});
const otherInstance = myTemplate({foo: 'other value', bar: 42});
【讨论】:
据我所知,您不能,至少不能尝试(至少使用公共 API)。
最好的选择是简单地使用已经存在的选项来渲染它:
const myTemplate = html`
<my-component .foo=${'bar'}>
</my-component>
`;
这应该是您 99.9% 的时间使用的方法。如果由于某种原因您真的无法做到这一点,您需要继续将模板渲染到某个占位符元素,然后使用 DOM 对其进行修改:
const div = document.createElement('div');
render(myTemplate, div);
div.querySelector('my-component').foo = 'bar';
【讨论】: