是否有使用 jsViews/jsRender 和 Web 组件作为模板引擎的用例?

我正在编写一些 Web 组件,我想使用 jsViews $.link 功能作为我的模板引擎。我已经能够使用 $.render 来替换 ShadowRoot 克隆内容的 .innerHTML,但我只能通过以下方式使用 $.link 。只是看起来“肮脏”,必须添加一个额外的 div 来链接。有一个更好的方法吗?这里有任何性能问题吗?:


const template = document.createElement('template');

template.innerHTML = `<div id="todo-item-tmpl"></div>`;


class TodoItem extends HTMLElement {

    constructor() {

        this._tmpl = $.templates('#todoItems');

        this._shadowRoot = this.attachShadow({ 'mode': 'open' });

        this._shadowRoot.appendChild(template.content.cloneNode(true));


        this._todoTmpl = this._shadowRoot.querySelector('#todo-item-tmpl');

        this._tmpl.link(this._todoTmpl, this._myDataObj);

    }

}


慕姐4208626
浏览 91回答 1
1回答

慕码人2483693

这是可能的方法,如示例的修改版本所示:https://jsfiddle.net/BorisMoore/z9wnyh5q/。它们不是将模板定义为脚本元素的内容,而是使用标记字符串来定义 - 以保留 Web 组件本身的 HTML 标记。<html>&nbsp; <head>...</head>&nbsp; <body>&nbsp; &nbsp; <to-do-app></to-do-app>&nbsp; </body></html>项目模板可以是全局定义的命名模板,$.templates("todoItemTmpl", todoItemTmpl}&nbsp; // markup string for item template或者可以将主模板作为资源(https://www.jsviews.com/#d.templates@tmpl-resources),以实现更好的封装:this._tmpl = $.templates({&nbsp; markup: todoappTmpl, // markup string&nbsp; templates: {todoItemTmpl: todoItemTmpl}&nbsp; // markup string for item template});this._tmpl.link(this._wrapper, this._todos, this);对(&nbsp;https://www.jsviews.com/#jsvtmpllink&nbsp;)的调用需要将 HTML 元素(或 jQuery 选择器)作为第一个参数,该元素是包装呈现的数据链接内容的容器元素。它不能直接是文档片段(影子根),因此您需要提供包装元素(并且还可以选择插入样式元素),例如通过以下代码:// Create a wrapper elementthis._wrapper = document.createElement('span');// and a style element...this._style = document.createElement('style');this._style.textContent = todoappStyle; // Stylesheet markup// Both inserted under the shadow rootthis._shadowRoot = this.attachShadow({ mode: "open" });this._shadowRoot.append(this._style, this._wrapper);// Render and data-linkthis._tmpl.link(this._wrapper, this._todos, this);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript