javascript - 为什么我不能将我的设置器用于带有模板的纯 JS 中的自定义元素?
问题描述
我对 Web 组件还很陌生,并且一直在试图弄清楚这些东西是如何工作的。在执行创建模板的推荐过程时,然后将其克隆到我的shadowRoot
我可以在我的 chrome 元素中看到它们,但不能在网页本身上看到它们。
例如:
import './components/ingredients/ingredients-table';
const template = document.createElement('template');
template.innerHTML = `
<h3>Add some ingredients</h3>
<ingredients-table id="hehe"></ingredients-table>
`
class App extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: 'open' });
this._shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
console.log(this._shadowRoot.querySelector('ingredients-table').id)
this._shadowRoot.querySelector('ingredients-table').ingredients = [
"1 tbsp, cinnamon extract",
"2 tbsp, cinnamon extract",
"3 tbsp, cinnamon extract",
"4 tbsp, cinnamon extract",
"5 tbsp, cinnamon extract",
"6 tbsp, cinnamon extract",
];
}
}
window.customElements.define('main-app', App);
window.addEventListener('load', () => {
const main = document.querySelector('main');
const app = document.createElement('main-app');
main.appendChild(app);
});
这表明了
这一点,这反过来意味着<ingredients-table>
的 set 功能不起作用
但是当我将构造函数行更改this._shadowRoot.appendChild(template.content.cloneNode(true));
为
this._shadowRoot.innerHTML = `
<h3>Add some ingredients</h3>
<ingredients-table id="hehe"></ingredients-table>
`
我明白了
有人可以澄清这到底是如何工作的吗?谢谢
这是一个代码笔: https ://codepen.io/aishmitkhurana/pen/wvaKWBL ?editors=0010
解决方案
您的错误是(简单)错字
挖掘完你的 CodePen
https://codepen.io/aishmitkhurana/pen/wvaKWBL?editors=0010
你的代码:
const template = document.createElement('template');
template.innerHTML = `
<h3>Add some ingredients</h3>
<ingredients-table></ingredients-table>
<recipe-steps></recipe-steps>`
...more code...
const template2 = document.createElement('template');
template <--TYPO .innerHTML = `
<table>
<ingredients-list></ingredients-list>
<tr>
<input
id="ingredients-input"
placeholder="e.g. 3/4 tbsp cinnamon powder"
>
</tr>
</table>`
您正在将第二个 HTML分配给第一个 模板
您的 F12 开发控制台清楚地表明:
对于该行:
this._shadowRoot.querySelector('ingredients-table').ingredients =
因为EMPTY模板中没有 <ingredients-table> 元素2
推荐阅读
- python-requests - 我收到错误 json.decoder.JSONDecodeError: while running a python code
- sql - SQL左连接,连接列中缺少数据
- hadoop - 手动启动 hdp 服务的顺序是什么?
- powershell - PowerShell MDB 查询 - 脚本在 Access 中而不是在 PowerShell 中工作
- gcc - 如何在 riscv-test 中编译 exp bechmark
- java - 如何使用 lambda 从 List<> 中获取总和和最低日期
- php - Laravel 多态关系返回 NULL
- r - 您如何使用 R 中的一个池连接和 dplyr 查询位于同一主机上的不同数据库?
- c - qsort 的自然排序不起作用
- c# - 组合框更改时不会调用 DataGrid RowValidationRule