Последняя активность 10 months ago

此範例展示如何在 Streamlit 應用中嵌入 Lit Web Component,而不依賴 CDN。使用 Web Components 技術,可封裝自訂 UI 元件,並透過 JavaScript 互動,適用於建立模組化的前端元件,提升 Web 應用的可維護性與重用性。

timmy ревизий этого фрагмента 10 months ago. К ревизии

1 file changed, 55 insertions

streamlit_lit_web_component.py(файл создан)

@@ -0,0 +1,55 @@
1 + import streamlit as st
2 + import streamlit.components.v1 as components
3 +
4 + st.title("使用 Lit Web Component (無 CDN)")
5 +
6 + lit_component = """
7 + <script type="module">
8 + class MyLitComponent extends HTMLElement {
9 + constructor() {
10 + super();
11 + this.attachShadow({ mode: 'open' });
12 + this.shadowRoot.innerHTML = `
13 + <style>
14 + :host {
15 + display: block;
16 + text-align: center;
17 + padding: 10px;
18 + border: 2px solid #007bff;
19 + border-radius: 8px;
20 + background-color: #f8f9fa;
21 + width: 100%;
22 + max-width: 400px;
23 + margin: auto;
24 + }
25 + h2 {
26 + color: #007bff;
27 + }
28 + button {
29 + padding: 10px 20px;
30 + font-size: 16px;
31 + cursor: pointer;
32 + background-color: #007bff;
33 + color: white;
34 + border: none;
35 + border-radius: 4px;
36 + margin-top: 10px;
37 + }
38 + </style>
39 + <h2>這是一個 Lit Web Component</h2>
40 + <p>使用 Lit 來建立的自訂元件</p>
41 + <button id="btn">點擊我</button>
42 + `;
43 + this.shadowRoot.getElementById("btn").addEventListener("click", () => {
44 + alert("你點擊了 Lit 按鈕!");
45 + });
46 + }
47 + }
48 +
49 + customElements.define('my-lit-component', MyLitComponent);
50 + </script>
51 +
52 + <my-lit-component></my-lit-component>
53 + """
54 +
55 + components.html(lit_component, height=250)
Новее Позже