最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談Vue插槽實(shí)現(xiàn)原理

 更新時(shí)間:2021年06月29日 15:02:30   作者:Gerryli  
vue.js的靈魂是組件,而組件的靈魂是插槽。借助于插槽,我們能最大程度上實(shí)現(xiàn)組件復(fù)用。本文主要是對(duì)插槽的實(shí)現(xiàn)機(jī)制進(jìn)行詳細(xì)概括總結(jié),在某些場(chǎng)景中,有一定的用處

一、樣例代碼

<!-- 子組件comA -->
<template>
  <div class='demo'>
    <slot><slot>
    <slot name='test'></slot>
    <slot name='scopedSlots' test='demo'></slot>
  </div>
</template>
<!-- 父組件 -->
<comA>
  <span>這是默認(rèn)插槽</span>
  <template slot='test'>這是具名插槽</template>
  <template slot='scopedSlots' slot-scope='scope'>這是作用域插槽(老版){{scope.test}}</template>
  <template v-slot:scopedSlots='scopeProps' slot-scope='scope'>這是作用域插槽(新版){{scopeProps.test}}</template>
</comA>

二、透過(guò)現(xiàn)象看本質(zhì)

插槽的作用是實(shí)現(xiàn)內(nèi)容分發(fā),實(shí)現(xiàn)內(nèi)容分發(fā),需要兩個(gè)條件:

  • 占位符
  • 分發(fā)內(nèi)容

組件內(nèi)部定義的slot標(biāo)簽,我們可以理解為占位符,父組件中插槽內(nèi)容,就是要分發(fā)的內(nèi)容。插槽處理本質(zhì)就是將指定內(nèi)容放到指定位置。廢話不多說(shuō),從本篇文章中,將能了解到:

  • 插槽的實(shí)現(xiàn)原理
  • render方法中如何使用插槽

三、實(shí)現(xiàn)原理

vue組件實(shí)例化順序?yàn)椋焊附M件狀態(tài)初始化(datacomputed、watch...) --> 模板編譯 --> 生成render方法 --> 實(shí)例化渲染watcher --> 調(diào)用render方法,生成VNode --> patch VNode,轉(zhuǎn)換為真實(shí)DOM --> 實(shí)例化子組件 --> ......重復(fù)相同的流程 --> 子組件生成的真實(shí)DOM掛載到父組件生成的真實(shí)DOM上,掛載到頁(yè)面中 --> 移除舊節(jié)點(diǎn)

從上述流程中,可以推測(cè)出:

1.父組件模板解析在子組件之前,所以父組件首先會(huì)獲取到插槽模板內(nèi)容

2.子組件模板解析在后,所以在子組件調(diào)用render方法生成VNode時(shí),可以借助部分手段,拿到插槽的VNode節(jié)點(diǎn)

3.作用域插槽可以獲取子組件內(nèi)變量,因此作用域插槽的VNode生成,是動(dòng)態(tài)的,即需要實(shí)時(shí)傳入子組件的作用域scope

整個(gè)插槽的處理階段大致分為三步:

  • 編譯
  • 生成渲染模板
  • 生成VNode

以下面代碼為例,簡(jiǎn)要概述插槽運(yùn)轉(zhuǎn)的過(guò)程。

<div id='app'>
  <test>
    <template slot="hello">
      123
    </template>
  </test>
</div>
<script>
  new Vue({
    el: '#app',
    components: {
      test: {
        template: '<h1>' +
          '<slot name="hello"></slot>' +
          '</h1>'
      }
    }
  })
</script>

四、父組件編譯階段

編譯是將模板文件解析成AST語(yǔ)法樹(shù),會(huì)將插槽template解析成如下數(shù)據(jù)結(jié)構(gòu):

{
  tag: 'test',
  scopedSlots: { // 作用域插槽
    // slotName: ASTNode,
    // ...
  }
  children: [
    {
      tag: 'template',
      // ...
      parent: parentASTNode,
      children: [ childASTNode ], // 插槽內(nèi)容子節(jié)點(diǎn),即文本節(jié)點(diǎn)123
      slotScope: undefined, // 作用域插槽綁定值
      slotTarget: "\"hello\"", // 具名插槽名稱
      slotTargetDynamic: false // 是否是動(dòng)態(tài)綁定插槽
      // ...
    }
  ]
}

五、父組件生成渲染方法

根據(jù)AST語(yǔ)法樹(shù),解析生成渲染方法字符串,最終父組件生成的結(jié)果如下所示,這個(gè)結(jié)構(gòu)和我們直接寫(xiě)render方法一致,本質(zhì)都是生成VNode, 只不過(guò)_chthis.$createElement的縮寫(xiě)。

with(this){
  return _c('div',{attrs:{"id":"app"}},
  [_c('test',
    [
      _c('template',{slot:"hello"},[_v("\n      123\n    ")])],2)
    ],
  1)
}

六、父組件生成VNode

調(diào)用render方法,生成VNode,VNode具體格式如下:

{
  tag: 'div',
  parent: undefined,
  data: { // 存儲(chǔ)VNode配置項(xiàng)
    attrs: { id: '#app' }
  },
  context: componentContext, // 組件作用域
  elm: undefined, // 真實(shí)DOM元素
  children: [
    {
      tag: 'vue-component-1-test',
      children: undefined, // 組件為頁(yè)面最小組成單元,插槽內(nèi)容放放到子組件中解析
      parent: undefined,
      componentOptions: { // 組件配置項(xiàng)
        Ctor: VueComponentCtor, // 組件構(gòu)造方法
        data: {
          hook: {
            init: fn, // 實(shí)例化組件調(diào)用方法
            insert: fn,
            prepatch: fn,
            destroy: fn
          },
          scopedSlots: { // 作用域插槽配置項(xiàng),用于生成作用域插槽VNode
            slotName: slotFn
          }
        },
        children: [ // 組件插槽節(jié)點(diǎn)
          tag: 'template',
          propsData: undefined, // props參數(shù)
          listeners: undefined,
          data: {
            slot: 'hello'
          },
          children: [ VNode ],
          parent: undefined,
          context: componentContext // 父組件作用域
          // ...
        ] 
      }
    }
  ],
  // ...
}

vue中,組件是頁(yè)面結(jié)構(gòu)的基本單元,從上述的VNode中,我們也可以看出,VNode頁(yè)面層級(jí)結(jié)構(gòu)結(jié)束于test組件,test組件children處理會(huì)在子組件初始化過(guò)程中處理。子組件構(gòu)造方法組裝與屬性合并在vue-dev\src\core\vdom\create-component.js createComponent方法中,組件實(shí)例化調(diào)用入口是在vue-dev\src\core\vdom\patch.js createComponent方法中。

七、子組件狀態(tài)初始化

實(shí)例化子組件時(shí),會(huì)在initRender -> resolveSlots方法中,將子組件插槽節(jié)點(diǎn)掛載到組件作用域vm中,掛載形式為vm.$slots = {slotName: [VNode]}形式。

八、子組件編譯階段

子組件在編譯階段,會(huì)將slot節(jié)點(diǎn),編譯成以下AST結(jié)構(gòu):

{
  tag: 'h1',
  parent: undefined,
  children: [
    {
      tag: 'slot',
      slotName: "\"hello\"",
      // ...
    }
  ],
  // ...
}

九、子組件生成渲染方法

生成的渲染方法如下,其中_trenderSlot方法的簡(jiǎn)寫(xiě),從renderSlot方法,我們就可以直觀的將插槽內(nèi)容與插槽點(diǎn)聯(lián)系在一起。

// 渲染方法
with(this){
  return _c('h1',[ _t("hello") ], 2)
}
// 源碼路徑:vue-dev\src\core\instance\render-helpers\render-slot.js
export function renderSlot (
  name: string,
  fallback: ?Array<VNode>,
  props: ?Object,
  bindObject: ?Object
): ?Array<VNode> {
  const scopedSlotFn = this.$scopedSlots[name]
  let nodes
  if (scopedSlotFn) { // scoped slot
    props = props || {}
    if (bindObject) {
      if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
        warn(
          'slot v-bind without argument expects an Object',
          this
        )
      }
      props = extend(extend({}, bindObject), props)
    }
    // 作用域插槽,獲取插槽VNode
    nodes = scopedSlotFn(props) || fallback
  } else {
    // 獲取插槽普通插槽VNode
    nodes = this.$slots[name] || fallback
  }

  const target = props && props.slot
  if (target) {
    return this.$createElement('template', { slot: target }, nodes)
  } else {
    return nodes
  }
}

作用域插槽與具名插槽區(qū)別

<!-- demo -->
<div id='app'>
  <test>
      <template slot="hello" slot-scope='scope'>
        {{scope.hello}}
      </template>
  </test>
</div>
<script>
    var vm = new Vue({
        el: '#app',
        components: {
            test: {
                data () {
                    return {
                        hello: '123'
                    }
                },
                template: '<h1>' +
                    '<slot name="hello" :hello="hello"></slot>' +
                  '</h1>'
            }
        }
    })

</script>

作用域插槽與普通插槽相比,主要區(qū)別在于插槽內(nèi)容可以獲取到子組件作用域變量。由于需要注入子組件變量,相比于具名插槽,作用域插槽有以下幾點(diǎn)不同:

作用域插槽在組裝渲染方法時(shí),生成的是一個(gè)包含注入作用域的方法,相對(duì)于createElement生成VNode,多了一層注入作用域方法包裹,這也就決定插槽VNode作用域插槽是在子組件生成VNode時(shí)生成,而具名插槽是在父組件創(chuàng)建VNode時(shí)生成。_uresolveScopedSlots,其作用為將節(jié)點(diǎn)配置項(xiàng)轉(zhuǎn)換為{scopedSlots: {slotName: fn}}形式。

with (this) {
        return _c('div', {
            attrs: {
                "id": "app"
            }
        }, [_c('test', {
            scopedSlots: _u([{
                key: "hello",
                fn: function(scope) {
                    return [_v("\n        " + _s(scope.hello) + "\n      ")]
                }
            }])
        })], 1)
    }

子組件初始化時(shí)會(huì)處理具名插槽節(jié)點(diǎn),掛載到組件$slots中,作用域插槽則在renderSlot中直接被調(diào)用

除此之外,其他流程大致相同。插槽作用機(jī)制不難理解,關(guān)鍵還是模板解析與生成render函數(shù)這兩步內(nèi)容較多,流程較長(zhǎng),比較難理解。

十、使用技巧

通過(guò)以上解析,能大概了解插槽處理流程。工作中大部分都是用模板來(lái)編寫(xiě)vue代碼,但是某些時(shí)候模板有一定的局限性,需要借助于render方法放大vue的組件抽象能力。那么在render方法中,我們插槽的使用方法如下:

10.1、具名插槽

插槽處理一般分為兩塊:

  • 父組件:父組件只需要寫(xiě)成模板編譯成的渲染方法即可,即指定插槽slot名稱
  • 子組件:由于子組件時(shí)直接拿父組件初始化階段生成的VNode,所以子組件只需要將slot標(biāo)簽替換為父組件生成的VNode,子組件在初始化狀態(tài)時(shí)會(huì)將具名插槽掛載到組件$slots屬性上。
<div id='app'>
<!--  <test>-->
<!--    <template slot="hello">-->
<!--      123-->
<!--    </template>-->
<!--  </test>-->
</div>
<script>
  new Vue({
    // el: '#app',
    render (createElement) {
      return createElement('test', [
        createElement('h3', {
          slot: 'hello',
          domProps: {
            innerText: '123'
          }
        })
      ])
    },
    components: {
      test: {
        render(createElement) {
          return createElement('h1', [ this.$slots.hello ]);
        }
        // template: '<h1>' +
        //   '<slot name="hello"></slot>' +
        //   '</h1>'
      }
    }
  }).$mount('#app')
</script>

10.2、作用域插槽

作用域插槽使用比較靈活,可以注入子組件狀態(tài)。作用域插槽 + render方法,對(duì)于二次組件封裝作用非常大。舉個(gè)栗子,在對(duì)ElementUI table組件進(jìn)行基于JSON數(shù)據(jù)封裝時(shí),作用域插槽用處就非常大了。

<div id='app'>
<!--  <test>-->
<!--    <span slot="hello" slot-scope='scope'>-->
<!--      {{scope.hello}}-->
<!--    </span>-->
<!--  </test>-->
</div>
<script>
  new Vue({
    // el: '#app',
    render (createElement) {
      return createElement('test', {
        scopedSlots:{
          hello: scope => { // 父組件生成渲染方法中,最終轉(zhuǎn)換的作用域插槽方法和這種寫(xiě)法一致
            return createElement('span', {
              domProps: {
                innerText: scope.hello
              }
            })
          }
        }
      })
    },
    components: {
      test: {
        data () {
          return {
            hello: '123'
          }
        },
        render (createElement) {
          // 作用域插槽父組件傳遞過(guò)來(lái)的是function,需要手動(dòng)調(diào)用生成VNode
          let slotVnode = this.$scopedSlots.hello({ hello: this.hello })
          return createElement('h1', [ slotVnode ])
        }
        // template: '<h1>' +
        //   '<slot name="hello" :hello="hello"></slot>' +
        //   '</h1>'
      }
    }
  }).$mount('#app')

</script>

以上就是淺談Vue插槽實(shí)現(xiàn)原理的詳細(xì)內(nèi)容,更多關(guān)于Vue插槽的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解用vue2.x版本+adminLTE開(kāi)源框架搭建后臺(tái)應(yīng)用模版

    詳解用vue2.x版本+adminLTE開(kāi)源框架搭建后臺(tái)應(yīng)用模版

    這篇文章主要介紹了用vue2.x版本+adminLTE開(kāi)源框架 搭建后臺(tái)應(yīng)用模版,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-03-03
  • Vue3刷新頁(yè)面報(bào)錯(cuò)404的解決方法

    Vue3刷新頁(yè)面報(bào)錯(cuò)404的解決方法

    本文主要介紹了Vue3刷新頁(yè)面報(bào)錯(cuò)404的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • vue+flask實(shí)現(xiàn)視頻合成功能(拖拽上傳)

    vue+flask實(shí)現(xiàn)視頻合成功能(拖拽上傳)

    這篇文章主要介紹了vue+flask實(shí)現(xiàn)視頻合成功能(拖拽上傳),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • 詳解關(guān)于Vue版本不匹配問(wèn)題(Vue packages version mismatch)

    詳解關(guān)于Vue版本不匹配問(wèn)題(Vue packages version mismatch)

    這篇文章主要介紹了詳解關(guān)于Vue版本不匹配問(wèn)題(Vue packages version mismatch),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-09-09
  • vue實(shí)現(xiàn)會(huì)議室拖拽布局排座功能

    vue實(shí)現(xiàn)會(huì)議室拖拽布局排座功能

    vue-draggable-resizable-gorkys是一更強(qiáng)大的拖拽組件,可以隨意拖拽,有點(diǎn)坐標(biāo),會(huì)議室拖拽布局排座是vue-draggable結(jié)合vue-draggable-resizable-gorkys進(jìn)行開(kāi)發(fā)的,本文重點(diǎn)給大家介紹vue實(shí)現(xiàn)會(huì)議室拖拽布局排座,感興趣的朋友一起看看吧
    2023-11-11
  • 在 Vue.js中優(yōu)雅地使用全局事件的方法

    在 Vue.js中優(yōu)雅地使用全局事件的方法

    這篇文章主要介紹了在 Vue.js中優(yōu)雅地使用全局事件的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-02-02
  • Vue中使用pdf.js實(shí)現(xiàn)PDF文檔展示功能實(shí)例

    Vue中使用pdf.js實(shí)現(xiàn)PDF文檔展示功能實(shí)例

    最近做項(xiàng)目遇到在線預(yù)覽和下載pdf文件,試了多種pdf插件,例如jquery.media.js(ie無(wú)法直接瀏覽),最后選擇了pdf.js插件,這篇文章主要介紹了Vue中使用pdf.js實(shí)現(xiàn)PDF文檔展示功能的相關(guān)資料,需要的朋友可以參考下
    2025-04-04
  • vue 實(shí)現(xiàn)通過(guò)vuex 存儲(chǔ)值 在不同界面使用

    vue 實(shí)現(xiàn)通過(guò)vuex 存儲(chǔ)值 在不同界面使用

    今天小編就為大家分享一篇vue 實(shí)現(xiàn)通過(guò)vuex 存儲(chǔ)值 在不同界面使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • Element-Plus的ClickOutside指令導(dǎo)致內(nèi)存泄漏的解決辦法

    Element-Plus的ClickOutside指令導(dǎo)致內(nèi)存泄漏的解決辦法

    這篇文章給大家介紹了Element-Plus的ClickOutside指令導(dǎo)致內(nèi)存泄漏的解決辦法,文中給出了詳細(xì)的解決辦法,遇到同樣問(wèn)題的小伙伴可以參考閱讀一下本文
    2024-01-01
  • vue中使用elementUI組件手動(dòng)上傳圖片功能

    vue中使用elementUI組件手動(dòng)上傳圖片功能

    Vue是一套構(gòu)建用戶界面的框架, 開(kāi)發(fā)只需要關(guān)注視圖層, 它不僅易于上手,還便于與第三方庫(kù)或既有項(xiàng)目的整合。這篇文章主要介紹了vue中使用elementUI組件手動(dòng)上傳圖片,需要的朋友可以參考下
    2019-12-12

最新評(píng)論

七台河市| 赤壁市| 黔江区| 东乌| 宁海县| 巴林右旗| 巴林右旗| 叙永县| 阿城市| 平阴县| 江阴市| 崇州市| 阿图什市| 郸城县| 罗定市| 西盟| 永善县| 栾城县| 广元市| 南陵县| 元谋县| 左权县| 墨江| 建平县| 云梦县| 广州市| 临澧县| 金沙县| 新化县| 柳河县| 缙云县| 商水县| 清流县| 湖州市| 嘉荫县| 朝阳区| 神木县| 宁海县| 德化县| 牟定县| 兴和县|