欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3 構(gòu)建 Web Components使用詳解

 更新時(shí)間:2022年09月08日 15:39:43   作者:白云蒼狗  
這篇文章主要為大家介紹了Vue3 構(gòu)建 Web Components使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

有時(shí)候想寫一個(gè)無關(guān)框架組件,又不想用原生或者 Jquery 那套去寫,而且還要避免樣式?jīng)_突,用 Web Components 去做剛覺就挺合適的。但是現(xiàn)在 Web Components 使用起來還是不夠靈活,很多地方還是不太方便的,如果能和 MVVM 搭配使用就好了。

早在之前 Angular 就支持將組件構(gòu)建成 Web Components,Vue3 3.2+ 開始終于支持將組建構(gòu)建成 Web Components 了。正好最近想重構(gòu)下評(píng)論插件,于是上手試了試。

構(gòu)建 Web Components

vue 提供了一個(gè) defineCustomElement 方法,用來將 vue 組件轉(zhuǎn)換成一個(gè)擴(kuò)展至HTMLElement的自定義函數(shù)構(gòu)造函數(shù),使用方式和 defineComponent 參數(shù)api基本保持一致。

import { defineCustomElement } from 'vue' 
const MyVueElement = defineCustomElement({
  // 在此提供正常的 Vue 組件選項(xiàng)
  props: {},
  emits: {},
  template: `...`,
  // defineCustomElement 獨(dú)有特性: CSS 會(huì)被注入到隱式根 (shadow root) 中
  styles: [`/* inlined css */`]
})
// 注冊(cè) Web Components
customElements.define('my-vue-element', MyVueElement)

如果需要使用單文件,需要 @vitejs/plugin-vue@^1.4.0 或 vue-loader@^16.5.0 或更高版本工具。如果只是部分文件需要使用,可以將后綴改為 .ce.vue 。

若果需要將所有文件都構(gòu)建 Web Components 可以將 @vitejs/plugin-vue@^1.4.0 或 vue-loader@^16.5.0 的 customElement 配置項(xiàng)開啟。這樣不需要再使用 .ce.vue 后綴名了。

屬性

vue 會(huì)把所有的的 props 自定義元素的對(duì)象的 property 上,也會(huì)將自定義元素標(biāo)簽上的 attribute 做一個(gè)映射。

<com-demo type="a"></com-demo>
props:{
  type:String
}

因?yàn)?HTML 的 attribute 的只能是字符串,除了基礎(chǔ)類型(Boolean、Number) Vue 在映射時(shí)會(huì)幫忙做類型轉(zhuǎn)換,其他復(fù)雜類型則需要設(shè)置到 DOM property 上。

事件

在自定義元素中,通過 this.$emit 或在 setup 中的 emit 發(fā)出的事件會(huì)被調(diào)度為原生 CustomEvents。附加的事件參數(shù) (payload) 會(huì)作為數(shù)組暴露在 CustomEvent 對(duì)象的 details property 上。

插槽

編寫組件時(shí),可以想 vue 一樣,但是使用時(shí)只能原生的插槽語法,所以也不在支持作用域插槽。

子組件樣式問題

使用子組件嵌套的時(shí),有個(gè)坑的地方就是默認(rèn)不會(huì)將子組件里的樣式抽離出來。

父組件

<template>
    <div class="title">{{ title }}</div>
    <Childer />
</template>
<script>
import Childer from "./childer.vue"
export default {
    components: { Childer },
    data() {
        return {
            title: "父組件"
        }
    },
}
</script>
<style lang="less" scoped>
.title {
    padding: 10px;
    background-color: #eee;
    font-weight: bold;
}
</style>

子組件

<template>
    <div class="childer">{{ title }}</div>
</template>
<script>
export default {
    data() {
        return {
            title: "子組件"
        }
    },
}
</script>
<style lang="less" scoped>
.childer {
    padding: 10px;
    background-color: #222;
    color: #fff;
    font-weight: bold;
}
</style>

可以看到子組件的樣式?jīng)]有插入進(jìn)去,但是樣式隔離的標(biāo)識(shí)是有生成的 data-v-5e87e937。不知道vue官方后續(xù)會(huì)不會(huì)修復(fù)這個(gè)bug

查看組件是可以看到,子組件的樣式是有被抽離出來的,這樣就只需要自己注入進(jìn)去了。

將子組件樣式抽離插入到父組件里,參考這個(gè)的實(shí)現(xiàn)

import ComDemo from '~/demo/index.vue'
const deepStylesOf = ({ styles = [], components = {} }) => {
    const unique = array => [...new Set(array)];
    return unique([...styles, ...Object.values(components).flatMap(deepStylesOf)]);
}
// 將子組件樣式插入到父組件里
ComDemo.styles = deepStylesOf(ComDemo)
!customElements.get('com-demo') && customElements.define('com-demo', defineCustomElement(ComDemo))

完美解決子組件樣式問題

方法

defineCustomElement 構(gòu)建的組件默認(rèn)是不會(huì)將方法掛到 customElement 上的,看 Vue 源碼中,只有 _def(構(gòu)造函數(shù)),_instance(組件實(shí)例))。

如果想調(diào)用組件內(nèi)的方法,dom._instance.proxy.fun(),感覺實(shí)在不太優(yōu)雅。

我們當(dāng)然希望我們組件暴露的方法能像普通dom那樣直接 dom.fun() 去掉用,我們對(duì) defineCustomElement 稍作擴(kuò)展。

import { VueElement, defineComponent } from 'vue'
const defineCustomElement = (options, hydate) => {
    const Comp = defineComponent(options);
    class VueCustomElement extends VueElement {
        constructor(initialProps) {
            super(Comp, initialProps, hydate);
            if (Comp.methods) {
                Object.keys(Comp.methods).forEach(key => {
                    // 將所有非下劃線開頭方法 綁定到 元素上
                    if(!/^_/.test(key)){
                        this[key] = function (...res) {
                            if (this._instance) {
                                // 將方法thi改為 組件實(shí)例的proxy
                                return Comp.methods[key].call(this._instance.proxy, ...res)
                            } else {
                                throw new Error('未找到組件實(shí)例')
                            }
                        }
                    }
                })
            }
        }
    }
    VueCustomElement.def = Comp;
    return VueCustomElement;
}

總結(jié)

總體來說坑還是有不少的,如果僅僅需要構(gòu)建一些比較簡(jiǎn)單跨框架插件,使用這種方式來構(gòu)建 Web Components 也是一種不錯(cuò)的方案。

以上就是Vue3 構(gòu)建 Web Components使用詳解的詳細(xì)內(nèi)容,更多關(guān)于Vue3 構(gòu)建 Web Components的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論