我有一个自定义组件<app-list>
,我正试图将其扩展到<calcs-list>
中。
// app-list.html
<script>
window.customElements.define('app-list',
class AppList extends HTMLElement {
constructor() {
super();
}
}
);
</script>
在calcs-list.html中,我得到:
<link rel="import" href="app-list.html">
<script>
window.customElements.define('calcs-list',
class CalcsList extends AppList {
constructor() {
super();
console.log('CalcsList constructed');
}
}
);
</script>
但是,我得到了这个错误
calcs未捕获ReferenceError: AppList未在calcs-list.html:11中定义
第11行引用class CalcsList extends AppList {
这两个文件是同一文件夹的同级文件。在将app-list.html
导入calcs-list.html
时,我尝试使用绝对路径,但得到了相同的结果。
我还尝试将这两个组件导入到我的主index.html文件中:
//index.html
<link rel="import" href="/src/components/app-list.html">
<link rel="import" href="/src/components/calcs-list.html">
<app-list></app-list>
<calcs-list></calcs-list>
但体验同样的结果。
app-list
组件可以在我的应用程序中正常工作,没有任何问题。
我在这个问题上摸不着头脑,因为Web组件是相当新的,在线上没有太多的故障排除信息,特别是关于Web组件的V1。
谢谢!
发布于 2018-06-07 10:01:36
感谢@Supersharp,我重写了我的自定义组件声明:
// app-list.html
<script>
class AppList extends HTMLElement { ... }
customElements.define('app-list', AppList);
</script>
和calcs-list.html
<script>
class CalcsList extends AppList { ... }
customElements.define('calcs-list', CalcsList);
</script>
注意事项:如果在父元素(要扩展的元素)中使用id
声明标记,那么这将与扩展元素对super()
的调用冲突。
例如:
<template id="app-list">
...
</template>
解决此问题的方法是使用the Google Developers引用的JavaScript字符串文字,而根本不使用id
。
<script>
let template = document.createElement('template');
template.innerHTML = `
<style> ... </style>
<div> ... </div>
`;
class AppList extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'}).appendChild(template.content.cloneNode(true));
}
}
</script>
发布于 2018-06-07 07:33:48
这是因为当你写下:
customElements.define('app-list',
class AppList extends HTMLElement {}
);
类AppList
仅在define()
调用的作用域中定义。这就是为什么在第二个导入文件中使用它之后看不到它的原因。
相反,您应该首先定义类(全局),然后在自定义元素定义中使用它:
// app-list.html
<script>
class AppList extends HTMLElement {
constructor() {
super();
}
}
window.customElements.define('app-list', AppList);
</script>
https://stackoverflow.com/questions/50726718
复制相似问题