1 回答

TA貢獻1860條經驗 獲得超9個贊
這是可能的方法,如示例的修改版本所示:https://jsfiddle.net/BorisMoore/z9wnyh5q/。
它們不是將模板定義為腳本元素的內容,而是使用標記字符串來定義 - 以保留 Web 組件本身的 HTML 標記。
<html>
<head>...</head>
<body>
<to-do-app></to-do-app>
</body>
</html>
項目模板可以是全局定義的命名模板,
$.templates("todoItemTmpl", todoItemTmpl} // markup string for item template
或者可以將主模板作為資源(https://www.jsviews.com/#d.templates@tmpl-resources),以實現更好的封裝:
this._tmpl = $.templates({
markup: todoappTmpl, // markup string
templates: {todoItemTmpl: todoItemTmpl} // markup string for item template
});
this._tmpl.link(this._wrapper, this._todos, this);
對( https://www.jsviews.com/#jsvtmpllink )的調用需要將 HTML 元素(或 jQuery 選擇器)作為第一個參數,該元素是包裝呈現的數據鏈接內容的容器元素。它不能直接是文檔片段(影子根),因此您需要提供包裝元素(并且還可以選擇插入樣式元素),例如通過以下代碼:
// Create a wrapper element
this._wrapper = document.createElement('span');
// and a style element...
this._style = document.createElement('style');
this._style.textContent = todoappStyle; // Stylesheet markup
// Both inserted under the shadow root
this._shadowRoot = this.attachShadow({ mode: "open" });
this._shadowRoot.append(this._style, this._wrapper);
// Render and data-link
this._tmpl.link(this._wrapper, this._todos, this);
添加回答
舉報