[Web Component] using `part` to allow applying styling from outside the shadow DOM

Let's say we have a web component: 

import { getProductById } from "../services/Menu.js";
import { addToCart } from "../services/Order.js";

export default class DetailsPage extends HTMLElement {
  constructor() {
    super();

    this.root = this.attachShadow({ mode: "open" });

    const template = document.getElementById("details-page-template");
    const content = template.content.cloneNode(true);
    const styles = document.createElement("style");
    this.root.appendChild(content);
    this.root.appendChild(styles);

    async function loadCSS() {
      const request = await fetch("/components/DetailsPage.css");
      styles.textContent = await request.text();
    }
    loadCSS();
  }

  async renderData() {
    if (this.dataset.productId) {
      this.product = await getProductById(this.dataset.productId);
      this.root.querySelector("h2").textContent = this.product.name;
      this.root.querySelector("img").src = `/data/images/${this.product.image}`;
      this.root.querySelector(".description").textContent =
        this.product.description;
      this.root.querySelector(
        ".price"
      ).textContent = `$ ${this.product.price.toFixed(2)} ea`;
      this.root.querySelector("button").addEventListener("click", () => {
        addToCart(this.product.id);
        app.router.go("/order");
      });
    } else {
      alert("Invalid Product ID");
    }
  }

  connectedCallback() {
    this.renderData();
  }
}

customElements.define("details-page", DetailsPage);

 

The template for the web component:

<template id="details-page-template">
      <header>
        <a href="#" onclick="app.router.go('/'); event.preventDefault()"
          >&lt; Back</a
        >
        <h2></h2>
        <a></a>
      </header>
      <img src="" />
      <p class="description"></p>
      <p class="price"></p>
      <button>Add to cart</button>
    </template>

 

Let's say we want to apply styling from outside to the imgof the Web component. We cannot do it directly due to web compoennt has shadow DOM.

 

But we can add part attribute to enable this change

    <template id="details-page-template">
      <header>
        <a href="#" onclick="app.router.go('/'); event.preventDefault()"
          >&lt; Back</a
        >
        <h2></h2>
        <a></a>
      </header>
      <!--add part to open shadow DOM to outside, so css can access it-->
      <img src="" part="image" />
      <p class="description"></p>
      <p class="price"></p>
      <button>Add to cart</button>
    </template>

 

Now we can target the img by using css:

details-page::part(image) {
  margin-left: -10%;
  width: 120%;
}

 

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-08-20 [Supabase] Use Triggers to Automatically Update Your Supabase Tables
2021-08-20 [SAA + SAP] 31. Migrations
2020-08-20 [React] Using react-styleguidist for Component demo
2019-08-20 [GraphQL] Query Lists of Multiple Types using a Union in GraphQL
2019-08-20 [GraphQL] Query GraphQL Interface Types in GraphQL Playground
2019-08-20 [GraphQL] Reuse GraphQL Selection Sets with Fragments
2019-08-20 [GraphQL] Use an Input Type to Create an Account with a GraphQL Mutation
点击右上角即可分享
微信分享提示