How to stamp out template in self contained custom elements with vanilla js?

你说的曾经没有我的故事 提交于 2019-12-01 20:23:45

In a nutshell: if you use template literals then you shouldn't use <template> element.

You don't need to duplicate the template to keep the custom element and template codes together.

You can simply enclose your code in a self-executed function to be sure that the tmpl variable won't be overridden.

(function () {

var tmpl = `
    <h1 class="tarot-title"><slot name="title">NEED TITLE</slot></h1>
    <img src="${this.imageurl}" alt="">
    <p><slot name="subtitle">NEED A SUBTITLE</slot></p>`;


class BdTarot extends HTMLElement {
    constructor() {
        super()      
        this.attachShadow( { mode: 'open' } ) 
             .innerHTML = tmpl;
    }
}

customElements.define('bd-tarot', BdTarot);

})()
<bd-tarot>
<span slot="title">Queen</span>
</bd-tarot>

If you want to keep a local copy of the template, you can copy it in an instance variable (this.tmpl).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!