我正在尝试定义一个自定义元素并在HTML模板中使用它,但它没有显示,也没有从控制台记录任何内容。似乎元素不是这样定义的。
我做错了什么?我用的是webpack和TypeScript。
我定义了一个类,它扩展了top-bar.ts中的HTML元素
export class TopBar extends HTMLElement {
shadowDOM : ShadowRoot;
constructor() {
super();
console.log('from constructor');
this.shadowDOM = this.attachShadow({mode:"open"});
}
connectedCallback() : void {
this.render();
}
render() : void {
this.innerHTML = `
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<style>
.top-bar {
box-shadow: 0px 2px 10px 6px #ccc;
height: 40px;
}
.top-bar h5 {
margin-bottom: 0;
color: #273C75;
}
.top-bar img {
display: block;
width: 36px;
height: 36px;
margin-right: 0.5rem;
}
</style>
<nav class="top-bar d-flex justify-content-center align-items-center">
<img src="img/Beep-Signal.png" alt="">
<h5>LoRa Dashboard</h5>
</nav>
`
}
}
customElements.define("top-bar", TopBar);在index.ts中,我导入了TopBar。
import * as TopBar from './components/top-bar'在index.html中,我将顶部栏元素
<!DOCTYPE html>
<html>
<head>
<title>LoRa Dashboard</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<script src="bundle.js"></script>
<top-bar></top-bar>
</body>
</html>发布于 2020-07-21 11:18:21
所以过了一段时间,我终于发现top-bar.ts似乎没有包含在捆绑包中。
尽管我已经将top-bar.ts导入到index.ts中,但它似乎没有包含在其中,我怀疑是因为index.ts中没有使用top-bar.ts中的任何内容,只在HTML中使用(在测试时)。这就是为什么自定义元素永远不会被定义。
因此,我在top-bar.ts中添加了一个伪函数,并在index.ts中调用它,只是为了包含它。目前,这个方法适用于我的项目,而且我还是个TypeScript和JavaScript新手,但是我相信有更好的变通办法,而不是仅仅为了包含它而调用一个伪函数。
https://stackoverflow.com/questions/62971838
复制相似问题