我一直在阅读,但我没有找到任何东西,如果有可能在不同的 html 文件中定义并使用 ESModule 导入以与 shadowRoot 一起使用,可能吗?
index.html,我在其中定义了 2 个 javscript 模块并使用了我的组件<hello-world></hello-world>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First Component</title>
<meta name="description" content="My First Component">
<meta name="author" content="Ismael Rodriguez">
<script type="module" src="js/my-template.js"></script>
<script type="module" src="js/component.js"></script>
<!--
<template id="my-template">
<h2>Hello World</h2>
</template>
-->
</head>
<body>
<h1>Web Component</h1>
<hello-world></hello-world>
</body>
Run Code Online (Sandbox Code Playgroud)
js/my-template.js,在这个模块中只导出一个带有标签 html 的字符串。
export const template = `
<style>
h3 {
color: red;
font-family: helvetica;
}
</style>
<h3>Hello World</h3>
`;
Run Code Online (Sandbox Code Playgroud)
js/component.js,最后导入模块my-template.js。我发现这种方法可以使用 ESmodule 从我的模块中解释模板。我如何导入模板并在我的组件中使用(支持 Firefox)?
import {template} from './my-template.js';
class HelloWorld extends HTMLElement{
constructor(){
super();
let shadowRoot = this.attachShadow({mode: 'open'})
const t = this.createTemplate(template);
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);
/*console.log(template);
const t = document.querySelector('#my-template');
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);*/
}
createTemplate(html){
const template = document.createElement('template');
html = html.trim();
template.innerHTML = html;
return template;
}
}
window.customElements.define('hello-world',HelloWorld);
Run Code Online (Sandbox Code Playgroud)
您只能将 Javascript 文件导入为 ES6 模块。
如果要导入元素,则需要将其放入 Javascript 文件,例如使用模板文字字符串。
模板.js:
export var template = `<template>
<h1>Content title</h1>
<div>Content</div>
</template>`
Run Code Online (Sandbox Code Playgroud)
但这没有意义。相反,您可以直接定义内容模板。
模板.js:
export var literal1= `
<h1>Content title</h1>
<div>Content</div>
`
Run Code Online (Sandbox Code Playgroud)
索引.html:
<div id=host></div>
<script type="module">
import * as templates from './templates.js'
host.attachShadow( {mode:'open'} )
.innerHTML = templates.literal1
</script>
Run Code Online (Sandbox Code Playgroud)
或者,如果您想将 DOM 元素保留在 HTML 文件中,您可以使用 fetch() 导入文件,如这篇关于 HTML Imports 的文章中截取的代码所示。
| 归档时间: |
|
| 查看次数: |
1938 次 |
| 最近记录: |