[英]custom components - how to clone html template defined as js string literal?
I'm trying to understand how the different parts of vanilla web components work together. 我试图了解香草Web组件的不同部分如何协同工作。 I have defined a simple custom component and am trying to include a template. 我定义了一个简单的自定义组件,并试图包括一个模板。 I'm doing this since many browser vendors are not supporting html imports and moving towards using es6 modules instead. 我这样做是因为许多浏览器供应商都不支持html导入,而是转而使用es6模块。 Here's my web component: 这是我的网络组件:
var tmpl = `<template>
<h1>header</h1>
<p>copy</p>
</template>`;
class MyComponent extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let z = tmpl.cloneNode(true);
this.appendChild(z);
}
}
customElements.define('my-comopnent', MyComponent);
The error I get is Uncaught Type Error: cloneNode is not a function I imagine that has something to do with the way I am defining my template as a string. 我得到的错误是未捕获的类型错误:cloneNode不是一个函数,我认为这与我将模板定义为字符串的方式有关。
My question is this: how do I stamp out my template in a custom component where the template is defined as a javascript string literal? 我的问题是:如何在自定义组件中将模板标记为JavaScript字符串文字,以将其删除? Can I do so without additional dependencies or npm libraries? 我可以在没有其他依赖项或npm库的情况下这样做吗?
Looking at https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode cloneNode
is a method that is on the Node
interface. 查看https://developer.mozilla.org/zh-CN/docs/Web/API/Node/cloneNode cloneNode
是Node
界面上的一种方法。
In your code tmpl
is not a Node
but a string
. 在您的代码中, tmpl
不是Node
而是string
。
You need to do something like this at the top of your code: 您需要在代码顶部执行以下操作:
let tmpl = document.createElement('template');
tmpl.innerHTML = `
<h1>header</h1>
<p>copy</p>
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.