1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        vue3.0新特性teleport是啥,用起來真香(開闊視野!)

        共 2133字,需瀏覽 5分鐘

         ·

        2021-01-06 01:38

        前言

        vue2.0時(shí)代,我們經(jīng)常會(huì)有這樣的需求,寫代碼邏輯的時(shí)候希望將組件寫在某個(gè)模板之下,因?yàn)檫@樣我們很好的使用組件內(nèi)部的狀態(tài)數(shù)據(jù),控制組件的展示形態(tài)。但是從技術(shù)的角度上我們又希望將這段代碼移到DOMVue app之外的其他位置。

        舉個(gè)簡(jiǎn)單的例子,我們?cè)谑褂?code style="font-size: 14px;padding: 2px 4px;border-radius: 4px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);background-color: rgba(27, 31, 35, 0.05);font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace;word-break: break-all;">modal組件的時(shí)候,我們將它放在了我們的模板template里面,但是由于modal組件希望位于頁面的最上方,這時(shí)候我們將modal組件掛載在body上面是最好控制的,我們能夠很好的通過zIndex來控制modal的位置,當(dāng)他嵌套在templat里面的時(shí)候就不那么容易了。

        vue2.0中的實(shí)現(xiàn)

        vue2.0中我在寫這個(gè)組件的時(shí)候是通過手動(dòng)的形式來進(jìn)行掛載的,我寫了一個(gè)vue指令來進(jìn)行這個(gè)操作,幫助我將modal組件掛載到body上面去,專這樣也能夠很好的通過控制zIndex來控制modal的展示。

        function?insert(el)?{
        ??const?parent?=?el.parentNode;
        ??if?(parent?&&?parent?!==?document.body)?{
        ??????parent.removeChild(el);
        ??????document.body.appendChild(el);
        ??}
        }

        export?default?(typeof?window?!==?'undefined'???{
        ??inserted(el,?{?value?})?{
        ??????if?(value)?{
        ??????????insert(el);
        ??????}
        ??},
        ??componentUpdated(el,?{?value?})?{
        ??????if?(value)?{
        ??????????insert(el);
        ??????}
        ??},
        }?:?{});

        上面的代碼其實(shí)就是簡(jiǎn)單的將modal從他原始掛載的父節(jié)點(diǎn)移除,然后掛載到body上去,通過手動(dòng)的形式來重新掛載,能夠很好的解決這種問題,當(dāng)然上面只是簡(jiǎn)單的邏輯,如果需要考慮卸載等其他邏輯代碼還得增加。