在vue react中如何使用Web Components組件
在vue react中使用Web Components組件
1、web組件部分代碼(git地址)
(function () {
? ? // 配置模板
? ? const getEemplate = () => {
? ? ? ? // 創(chuàng)建模板
? ? ? ? const template = document.createElement('template');
? ? ? ? // 給模板設(shè)置id 方便查找
? ? ? ? template.id = 'userCardTemplate';
? ? ? ? template.innerHTML = `
? ? <style>
? ? ? ? :host {
? ? ? ? ? ? ? ? display: flex;
? ? ? ? ? ? ? ? align-items: center;
? ? ? ? ? ? ? ? width: 450px;
? ? ? ? ? ? ? ? height: 180px;
? ? ? ? ? ? ? ? background-color: #d4d4d4;
? ? ? ? ? ? ? ? border: 1px solid #d5d5d5;
? ? ? ? ? ? ? ? box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
? ? ? ? ? ? ? ? border-radius: 3px;
? ? ? ? ? ? ? ? overflow: hidden;
? ? ? ? ? ? ? ? padding: 10px;
? ? ? ? ? ? ? ? box-sizing: border-box;
? ? ? ? ? ? ? ? font-family: 'Poppins', sans-serif;
? ? ? ? ? ? }
? ? ? ? .image {
? ? ? ? ? ? ? ? flex: 0 0 auto;
? ? ? ? ? ? ? ? width: 160px;
? ? ? ? ? ? ? ? height: 160px;
? ? ? ? ? ? ? ? vertical-align: middle;
? ? ? ? ? ? ? ? border-radius: 5px;
? ? ? ? ? ? }
? ? ? ? .container {
? ? ? ? ? ? ? ? box-sizing: border-box;
? ? ? ? ? ? ? ? padding: 20px;
? ? ? ? ? ? ? ? height: 160px;
? ? ? ? ? ? }
? ? ? ? .container > .name {
? ? ? ? ? ? ? ? font-size: 20px;
? ? ? ? ? ? ? ? font-weight: 600;
? ? ? ? ? ? ? ? line-height: 1;
? ? ? ? ? ? ? ? margin: 0;
? ? ? ? ? ? ? ? margin-bottom: 5px;
? ? ? ? ? ? }
? ? ? ? .container > .email {
? ? ? ? ? ? ? ? font-size: 12px;
? ? ? ? ? ? ? ? opacity: 0.75;
? ? ? ? ? ? ? ? line-height: 1;
? ? ? ? ? ? ? ? margin: 0;
? ? ? ? ? ? ? ? margin-bottom: 15px;
? ? ? ? ? ? }
? ? ? ? .container > .button {
? ? ? ? ? ? ? ? padding: 10px 25px;
? ? ? ? ? ? ? ? font-size: 12px;
? ? ? ? ? ? ? ? border-radius: 5px;
? ? ? ? ? ? ? ? text-transform: uppercase;
? ? ? ? ? ? }
? ? ?</style>
? ? <img class="image">
? ? <div class="container">
? ? ? ? <p class="name"></p>
? ? ? ? <p class="email"></p>
? ? ? ? <button class="button">Follow John</button>
? ? </div>
? ? `;
? ? ? ? return template;
? ? };
? ? // 講模板放到dom結(jié)構(gòu)中去
? ? const createEemplate = () => {
? ? ? ? document.body.appendChild(getEemplate());
? ? };
? ? createEemplate();
? ? class UserCard extends HTMLElement {
? ? ? ? constructor() {
? ? ? ? ? ? super();
? ? ? ? ? ? this.creatShadow();
? ? ? ? ? ? // 此處防止vue等框架類型的組件使用時 生命周期導(dǎo)致的參數(shù)異常 因此延遲綁定參數(shù)
? ? ? ? ? ? setTimeout(() => {
? ? ? ? ? ? ? ? this.creatContent();
? ? ? ? ? ? });
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 封閉內(nèi)部dom
? ? ? ? ?*/
? ? ? ? creatShadow() {
? ? ? ? ? ? this.shadow = this.attachShadow({mode: 'closed'});
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 創(chuàng)建內(nèi)部顯示內(nèi)容
? ? ? ? ?*/
? ? ? ? creatContent() {
? ? ? ? ? ? var templateElem = document.getElementById('userCardTemplate');
? ? ? ? ? ? var content = templateElem.content.cloneNode(true);
? ? ? ? ? ? content.querySelector('img').setAttribute('src', this.getAttribute('image'));
? ? ? ? ? ? content.querySelector('.container>.name').innerText = this.getAttribute('name');
? ? ? ? ? ? content.querySelector('.container>.email').innerText = this.getAttribute('email');
? ? ? ? ? ? this.shadow.appendChild(content);
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 當(dāng)自定義元素第一次被連接到文檔DOM時被調(diào)用
? ? ? ? ?* 相當(dāng)于mounted
? ? ? ? ?*/
? ? ? ? connectedCallback() {
? ? ? ? ? ? console.log('connectedCallback')
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 當(dāng)自定義元素與文檔DOM斷開連接時被調(diào)用。
? ? ? ? ?* 與beforeDestroy類似
? ? ? ? ?*/
? ? ? ? disconnectedCallback() {
? ? ? ? ? ? console.log('disconnectedCallback')
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 當(dāng)自定義元素被移動到新文檔時被調(diào)用。
? ? ? ? ?*/
? ? ? ? adoptedCallback() {
? ? ? ? ? ? console.log('adoptedCallback')
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 暴露哪些屬性可以被監(jiān)聽
? ? ? ? ?* @returns {string[]}
? ? ? ? ?*/
? ? ? ? static get observedAttributes() {
? ? ? ? ? ? return ['image', 'name', 'email']
? ? ? ? }
? ? ? ? /**
? ? ? ? ?* 當(dāng)自定義元素的一個屬性被增加、移除或更改時被調(diào)用。
? ? ? ? ?*/
? ? ? ? attributeChangedCallback() {
? ? ? ? ? ? console.log('attributeChangedCallback')
? ? ? ? }
? ? }
? ? window.customElements.define('user-card', UserCard);
})();
? ? ? ? ? ? /**
? ? ? ? ? ? ?* 自定義事件
? ? ? ? ? ? */
? ? ? ? ? ? this.dispatchEvent(new CustomEvent('submit', {
? ? ? ? ? ? ?detail: {
? ? ? ? ? ? ? data: {}
? ? ? ? ? ? ?}
? ? ? ? ? ? }));
? ? ? ? ? ? this.dispatchEvent(new CustomEvent('afterSubmit', {
? ? ? ? ? ? ?detail: {
? ? ? ? ? ? ? data: {}
? ? ? ? ? ? ?}
? ? ? ? ? ? }));2、vue中使用部門代碼
在public目錄下得index.html中導(dǎo)入
<script src="./UserCard.js"></script>
<template>
? <div id="app">
? ? <user-card v-if="show" image="https://semantic-ui.com/images/avatar2/large/kristy.png"
? ? ? ? ? ? ? ?name="User Name"
? ? ? ? ? ? ? ?email="yourmail@some-email.com"
? ? ></user-card>
? ? ? <user-card
? ? ? ? ? ? ? image="https://semantic-ui.com/images/avatar2/large/kristy.png"
? ? ? ? ? ? ? name="test"
? ? ? ? ? ? ? email="yourmail@some-email.com"
? ? ? ></user-card>
? ? <button @click="onclick">
? ? ? 測試
? ? </button>
? </div>
</template>
<script>
export default {
? data: function() {
? ? return {
? ? ? show: true
? ? }
? },
? name: 'App',
? mounted() {
? },
? methods: {
? ? // 測試web組件生命周期
? ? onclick() {
? ? ? this.show = !this.show;
? ? }
? }
}
</script>
<style>
#app {
? font-family: Avenir, Helvetica, Arial, sans-serif;
? -webkit-font-smoothing: antialiased;
? -moz-osx-font-smoothing: grayscale;
? text-align: center;
? color: #2c3e50;
? margin-top: 60px;
}
</style>3、在react中使用
// submit事件 在點擊登錄時觸發(fā),傳遞的登錄信息在,detail字段中
// afterSubmit 在登錄數(shù)據(jù)下發(fā)服務(wù)端后觸發(fā) 用于處理登錄后的路由跳轉(zhuǎn)等邏輯
<user-card url="https://www.baidu.com/"
? ? ? ? ? ? ? ? ? user="account"
? ? ? ? ? ? ? ? ? password="password"
? ? ? ? ? ? ? ? ? id="form"
? ? ? ? ? ? ? ? ? style="background-image: url(/assets/background.jpg)"
? ? ? ? ? ? ? ? ? body-style="right: 200px;"
? ? ? ? ? ? ? ? ? title="系統(tǒng)">
? ? </user-card>
? ? <script>
? ? ? ? const form = document.querySelector('#form');
? ? ? ? form.addEventListener('submit', (data)=> {
? ? ? ? ?? ?console.log(data)
? ? ? ? });
? ? ? ? form.addEventListener('afterSubmit', (data)=> {
?? ? ? ? ? ?console.log(data)
? ? ? ? });
? ? </script>
/**
?* 處理react tsx中直接使用web components報錯問題
?*/
interface UserCardModuleProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
?? ?title: string,
?? ?...
}
declare global {
?? ?namespace JSX {
?? ??? ?interface IntrinsicElements {
?? ??? ??? ?'user-card': UserCardModuleProps
?? ??? ?}
?? ?}
}4、在html中使用
<!DOCTYPE html> <html> <head> ? ? <meta charset="utf-8"> ? ? <meta name="viewport" content="width=device-width"> ? ? <title>JS Bin</title> </head> <body> <user-card ? ? ? ? image="https://semantic-ui.com/images/avatar2/large/kristy.png" ? ? ? ? name="User Name" ? ? ? ? email="yourmail@some-email.com" ></user-card> <user-card ? ? ? ? image="https://semantic-ui.com/images/avatar2/large/kristy.png" ? ? ? ? name="test" ? ? ? ? email="yourmail@some-email.com" ></user-card> <script src="./public/UserCard.js"></script> <script > </script> </body> </html>
組件化統(tǒng)一標(biāo)準(zhǔn)——Web Components
Web Components是什么
一句話概括,Web Components是一個Web組件標(biāo)準(zhǔn)。現(xiàn)在的前端開發(fā)幾乎已經(jīng)離不開組件化開發(fā)了,無論是vue中的模板語法還是react中的JSX,都是把結(jié)構(gòu)、樣式和邏輯封裝成一個組件,采用組件復(fù)用來提高開發(fā)效率。
既然組件如此重要,Web Components就是提供瀏覽器底層的支持,不依賴各種框架的支持和webpack的編譯,讓我們也能使用組件。
Web Components通過一種標(biāo)準(zhǔn)化的非侵入的方式封裝一個組件,每個組件能組織好它自身的HTML、CSS、JavaScript,并且不會干擾頁面上的其他代碼。
Web Components的組成
Web Components由以下四個部分組成:

HTML templates
支持template標(biāo)簽和slot標(biāo)簽。slot標(biāo)簽支持動態(tài)替換模板中的HTML內(nèi)容,它用name屬性來作為唯一表示。template中的內(nèi)容被插入到DOM之前,不會渲染,它可以放在document中的任何位置。

HTML Imports
改造一下上面的例子,將template的內(nèi)容寫到一個新的main.html文件中,然后通過link引入。

Shadow DOM
Shadow DOM提供了一種健壯的封裝方式來做到頁面節(jié)點的隔離,避免全局樣式?jīng)_突,這也是Web Component的核心優(yōu)勢。


Shadow DOM中設(shè)置的樣式?jīng)]有影響外部<p>標(biāo)簽的樣式。
Custom elements
在custom element的構(gòu)造函數(shù)中,可以指定多個不同的回調(diào)函數(shù),它們將會在元素的不同生命時期被調(diào)用:
connectedCallback:當(dāng) custom element首次被插入文檔DOM時,被調(diào)用。disconnectedCallback:當(dāng) custom element從文檔DOM中刪除時,被調(diào)用。adoptedCallback:當(dāng) custom element被移動到新的文檔時,被調(diào)用。attributeChangedCallback: 當(dāng) custom element增加、刪除、修改自身屬性時,被調(diào)用。



總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
el-table實現(xiàn)嵌套表格的展示功能(完整代碼)
el-table中在嵌套一個el-table,這樣數(shù)據(jù)格式就沒問題了,主要就是樣式,將共同的列放到一列中,通過渲染自定義表頭render-header,將表頭按照合適的寬度渲染出來,本文給大家分享el-table實現(xiàn)嵌套表格的展示功能,感興趣的朋友一起看看吧2024-02-02
vue2前端調(diào)用WebSocket有消息進行通知代碼示例
在Vue項目中實現(xiàn)全局的消息鏈接監(jiān)聽主要涉及到了WebSocket技術(shù),這是一種雙向通信協(xié)議,允許客戶端與服務(wù)器之間實時、高效地交換數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于vue2前端調(diào)用WebSocket有消息進行通知的相關(guān)資料,需要的朋友可以參考下2024-07-07

