亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕姐4208626 2023-07-20 15:37:17
我正在編寫一些 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);    }}
查看完整描述

1 回答

?
慕碼人2483693

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);


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號