问题描述
我想知道是否有可能(我使用 ES6 和 Typescript)将我的 HTML 代码与我的组件分开,即将 HTML 代码包含到另一个文件的变量中.
I would like to know if it is possible (I am using ES6 and Typescript) to separate my HTML code from my components i.e. include the HTML code into a variable from another file.
目前我们正在以这样的结构编写所有 HTML:
Currently we are writing all HTML within a structure like this:
let html = `<h1>Hello</h1> world!`
当你有很多 HTML 时,这显然不是很酷.
Which is obviously not cool when you have a lot of HTML.
有没有办法将我的 HTML 与我的 Javascript 组件分开,以便我可以这样做:
Is there a way to separate my HTML from my Javascript component so I could do for example:
let html = include('index.html');
推荐答案
您可以使用 fetch()
.这是一个异步函数,因此您可以使用 async/await
或 Promises.
You could use fetch()
. It's an asynchronous function so you'll avec to use async/await
or Promises.
class MyComponent extends HTMLElement {
async connectedCallback() {
let res = await fetch( 'my-component.html' )
this.innerHTML = await res.text()
}
}
customElements.define( 'my-component', MyComponent )
这篇关于Web 组件,如何将 HTML 与代码分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!