监听DOM及标签自定义属性修改

<body>
    <div class="index">hello world</div>
    <button onclick="settagname()">更改blue-buy标签</button>
<script>
const prices = {
t_porsche: '66,00 €',
t_fendt: '54,00 €',
t_eicher: '58,00 €',
};
//es6 的类
class BlueBuy extends HTMLElement {
static get observedAttributes() {
console.log("初始化执行 observedAttributes");
//return 提前设置自定义属性名
return ['skus'];
}
connectedCallback() {
console.log("监听到blue-buy标签时执行");
this.render();
}
render() {
const sku = this.getAttribute('skus');
const price= prices[sku]||"你好";
this.innerHTML = `<button type="button">buy for ${price}</button>`;
}
attributeChangedCallback(attr, oldValue, newValue) {
console.log("skus 变化时执行",attr, oldValue, newValu);
this.render();
}
disconnectedCallback() {
console.log("修改标签执行");
}
}
window.customElements.define('blue-buy', BlueBuy);
function settagname() {
console.log("执行点击事件");
//设置标签自定义属性
document.querySelector('blue-buy').setAttribute('skus', 't_fendt');
}


</script>
//更多请看https://swearer23.github.io/micro-frontends/#parent-child-communication--dom-modification
posted @ 2022-02-17 11:34  波仔、  阅读(83)  评论(0编辑  收藏  举报