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

在Vue中使用HOC模式的實(shí)現(xiàn)

 更新時(shí)間:2020年08月23日 17:21:00   作者:zhangwinwin  
這篇文章主要介紹了在Vue中使用HOC模式的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

HOC是React常用的一種模式,但HOC只能是在React才能玩嗎?先來看看React官方文檔是怎么介紹HOC的:

高階組件(HOC)是React中用于復(fù)用組件邏輯的一種高級(jí)技巧。HOC自身不是ReactAPI的一部分,它是一種基于React的組合特性而形成的設(shè)計(jì)模式。

HOC它是一個(gè)模式,是一種思想,并不是只能在React中才能用。所以結(jié)合Vue的特性,一樣能在Vue中玩HOC。

HOC

HOC要解決的問題

并不是說哪種技術(shù)新穎,就得使用哪一種。得看這種技術(shù)能夠解決哪些痛點(diǎn)。

HOC主要解決的是可復(fù)用性的問題。在Vue中,這種問題一般是用Mixin解決的。Mixin是一種通過擴(kuò)展收集功能的方式,它本質(zhì)上是將一個(gè)對象的屬性拷貝到另一個(gè)對象上去。

最初React也是使用Mixin的,但是后面發(fā)現(xiàn)Mixin在React中并不是一種好的模式,它有以下的缺點(diǎn):

  • mixin與組件之間容易導(dǎo)致命名沖突
  • mixin是侵入式的,改變了原組件,復(fù)雜性大大提高。

所以React就慢慢的脫離了mixin,從而推薦使用HOC。并不是mixin不優(yōu)秀,只是mixin不適合React。

HOC是什么

HOC全稱:high-order component--也就是高階組件。具體而言,高階組件是參數(shù)為組件,返回值為新組件的函數(shù)。

而在React和Vue中組件就是函數(shù),所以的高階組件其實(shí)就是高階函數(shù),也就是返回一個(gè)函數(shù)的函數(shù)。

來看看HOC在React的用法:

function withComponent(WrappedComponent) {
  return class extends Component {
    componentDidMount () {
      console.log('已經(jīng)掛載完成')
    }
    render() {
      return <WrappedComponent {...props} />;
    }
  }
}

withComponent就是一個(gè)高階組件,它有以下特點(diǎn):

  • HOC是一個(gè)純函數(shù),且不應(yīng)該修改原組件
  • HOC不關(guān)心傳遞的props是什么,并且WrappedComponent不關(guān)心數(shù)據(jù)來源
  • HOC接收到的props應(yīng)該透傳給WrapperComponent

在Vue中使用HOC

怎么樣才能將Vue上使用HOC的模式呢?

我們一般書寫的Vue組件是這樣的:

<template>
 <div>
  <p>{{title}}</p>
  <button @click="changeTitle"></button>
 </div>
</template>

<script>
export default {
 name: 'ChildComponent',
 props: ['title'],
 methods: {
  changeTitle () {
    this.$emit('changeTitle');
  }
 }
}
</script>

而withComponet函數(shù)的功能是在每次掛載完成后都打印一句:已經(jīng)掛載完成。

既然HOC是替代mixin的,所以我們先用mixin書寫一遍:

export default {
  mounted () {
    console.log('已經(jīng)掛載完成')
  }
}

然后導(dǎo)入到ChildComponent中

import withComponent from './withComponent';
export default {
  ...
  mixins: ['withComponet'],
}

對于這個(gè)組件,我們在父組件中是這樣調(diào)用的

<child-component :title='title' @changeTitle='changeTitle'></child-component>

<script>
import ChildComponent from './childComponent.vue';
export default {
  ...
  components: {ChildComponent}
}
</script>

大家有沒有發(fā)現(xiàn),當(dāng)我們導(dǎo)入一個(gè)Vue組件時(shí),其實(shí)是導(dǎo)入一個(gè)對象。

export default {}

至于說組件是函數(shù),其實(shí)是經(jīng)過處理之后的結(jié)果。所以Vue中的高階組件也可以是:接收一個(gè)純對象,返回一個(gè)純對象。

所以改為HOC模式,是這樣的:

export default function withComponent (WrapperComponent) {
  return {
    mounted () {
      console.log('已經(jīng)掛載完成')
    },
    props: WrappedComponent.props,
    render (h) {
      return h(WrapperComponent, {
        on: this.$listeners,
        attrs: this.$attrs,
        props: this.$props
      })
    }
  }
}

注意{on: this.$listeners,attr: this.$attrs, props: this.props}這一句就是透傳props的原理,等價(jià)于React中的<WrappedComponent {...props} />;

this.$props是指已經(jīng)被聲明的props屬性,this.$attrs是指沒被聲明的props屬性。這一定要兩個(gè)一起透傳,缺少哪一個(gè),props都不完整。

為了通用性,這里使用了render函數(shù)來構(gòu)建,這是因?yàn)閠emplate只有在完整版的Vue中才能使用。

這樣似乎還不錯(cuò),但是還有一個(gè)重要的問題,在Vue組件中是可以使用插槽的。

比如:

<template>
 <div>
  <p>{{title}}</p>
  <button @click="changeTitle"></button>
  <slot></slot>
 </div>
</template>

在父組件中

<child-component :title='title' @changeTitle='changeTitle'>Hello, HOC</child-component>

可以用this.$solts訪問到被插槽分發(fā)的內(nèi)容。每個(gè)具名插槽都有其相應(yīng)的property,例如v-slot:foo中的內(nèi)容將會(huì)在this.$slots.foo中被找到。而default property包括了所有沒有被包含在具名插槽中的節(jié)點(diǎn),或v-slot:default的內(nèi)容。

所以在使用渲染函數(shù)書寫一個(gè)組件時(shí),訪問this.$slots最有幫助的。

先將this.$slots轉(zhuǎn)化為數(shù)組,因?yàn)殇秩竞瘮?shù)的第三個(gè)參數(shù)是子節(jié)點(diǎn),是一個(gè)數(shù)組

export default function withComponent (WrapperComponent) {
  return {
    mounted () {
         console.log('已經(jīng)掛載完成')
    },
    props: WrappedComponent.props,
    render (h) {
      const keys = Object.keys(this.$slots);
      const slotList = keys.reduce((arr, key) => arr.concat(this.$slots[key]), []);
      return h(WrapperComponent, {
        on: this.$listeners,
        attrs: this.$attrs,
        props: this.$props
      }, slotList)
    }
  }
}

總算是有模有樣了,但這還沒結(jié)束,你會(huì)發(fā)現(xiàn)使不使用具名插槽都一樣,最后都是按默認(rèn)插槽來處理的。

有點(diǎn)納悶,去看看Vue源碼中是怎么具名插槽的。
在src/core/instance/render.js文件中找到了initRender函數(shù),在初始化render函數(shù)時(shí)

const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)

這一段代碼是Vue解析并處理slot的。
將vm.$options._parentVnode賦值為vm.$vnode,也就是$vnode就是父組件的vnode。如果父組件存在,定義renderContext = vm.$vnode.context。renderContext就是父組件要渲染的實(shí)例。 然后把renderContext和$options._renderChildren作為參數(shù)傳進(jìn)resolveSlots()函數(shù)中。

接下里看看resolveSlots()函數(shù),在src/core/instance/render-helper/resolve-slots.js文件中

export function resolveSlots (
 children: ?Array<VNode>,
 context: ?Component
): { [key: string]: Array<VNode> } {
 if (!children || !children.length) {
  return {}
 }
 const slots = {}
 for (let i = 0, l = children.length; i < l; i++) {
  const child = children[i]
  const data = child.data
  // remove slot attribute if the node is resolved as a Vue slot node
  if (data && data.attrs && data.attrs.slot) {
   delete data.attrs.slot
  }
  // named slots should only be respected if the vnode was rendered in the
  // same context.
  if ((child.context === context || child.fnContext === context) &&
   data && data.slot != null
  ) {
   const name = data.slot
   const slot = (slots[name] || (slots[name] = []))
   if (child.tag === 'template') {
    slot.push.apply(slot, child.children || [])
   } else {
    slot.push(child)
   }
  } else {
   (slots.default || (slots.default = [])).push(child)
  }
 }
 // ignore slots that contains only whitespace
 for (const name in slots) {
  if (slots[name].every(isWhitespace)) {
   delete slots[name]
  }
 }
 return slots
}

重點(diǎn)來看里面的一段if語句

// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
 data && data.slot != null
) {
 const name = data.slot
 const slot = (slots[name] || (slots[name] = []))
 if (child.tag === 'template') {
  slot.push.apply(slot, child.children || [])
 } else {
  slot.push(child)
 }
} else {
 (slots.default || (slots.default = [])).push(child)
}

只有當(dāng)if ((child.context === context || child.fnContext === context) && data && data.slot != null ) 為真時(shí),才處理為具名插槽,否則不管具名不具名,都當(dāng)成默認(rèn)插槽處理

else {
 (slots.default || (slots.default = [])).push(child)
}

那為什么HOC上的if條件是不成立的呢?

這是因?yàn)橛捎贖OC的介入,在原本的父組件與子組件之間插入了一個(gè)組件--也就是HOC,這導(dǎo)致了子組件中訪問的this.$vode已經(jīng)不是原本的父組件的vnode了,而是HOC中的vnode,所以這時(shí)的this.$vnode.context引用的是高階組件,但是我們卻將slot透傳了,slot中的VNode的context引用的還是原來的父組件實(shí)例,所以就導(dǎo)致不成立。

從而都被處理為默認(rèn)插槽。

解決方法也很簡單,只需手動(dòng)的將slot中的vnode的context指向?yàn)镠OC實(shí)例即可。注意當(dāng)前實(shí)例 _self 屬性訪問當(dāng)前實(shí)例本身,而不是直接使用 this,因?yàn)?this 是一個(gè)代理對象。

export default function withComponent (WrapperComponent) {
  return {
    mounted () {
         console.log('已經(jīng)掛載完成')
    },
    props: WrappedComponent.props,
    render (h) {
      const keys = Object.keys(this.$slots);
      const slotList = keys.reduce((arr, key) => arr.concat(this.$slots[key]), []).map(vnode => {
        vnode.context = this._self
        return vnode
      });
      return h(WrapperComponent, {
        on: this.$listeners,
        attrs: this.$attrs,
        props: this.$props
      }, slotList)
    }
  }
}

而且scopeSlot與slot的處理方式是不同的,所以將scopeSlot一起透傳

export default function withComponent (WrapperComponent) {
  return {
    mounted () {
         console.log('已經(jīng)掛載完成')
    },
    props: WrappedComponent.props,
    render (h) {
      const keys = Object.keys(this.$slots);
      const slotList = keys.reduce((arr, key) => arr.concat(this.$slots[key]), []).map(vnode => {
        vnode.context = this._self
        return vnode
      });
      return h(WrapperComponent, {
        on: this.$listeners,
        attrs: this.$attrs,
        props: this.$props,
        scopedSlots: this.$scopedSlots
      }, slotList)
    }
  }
}

這樣就行了。

結(jié)尾

更多文章請移步樓主github,如果喜歡請點(diǎn)一下star,對作者也是一種鼓勵(lì)。

到此這篇關(guān)于在Vue中使用HOC模式的文章就介紹到這了,更多相關(guān)Vue使用HOC模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue關(guān)于下載文件常用的幾種方式

    vue關(guān)于下載文件常用的幾種方式

    這篇文章主要介紹了vue關(guān)于下載文件常用的幾種方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • vue.js實(shí)現(xiàn)含搜索的多種復(fù)選框(附源碼)

    vue.js實(shí)現(xiàn)含搜索的多種復(fù)選框(附源碼)

    這篇文章主要給大家介紹了利用vue.js實(shí)現(xiàn)含搜索的多種復(fù)選框的相關(guān)資料,文中給出了簡單的介紹,但提供了完整的實(shí)例源碼供大家下載學(xué)習(xí),相信對大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。
    2017-03-03
  • vue全局自定義指令-元素拖拽的實(shí)現(xiàn)代碼

    vue全局自定義指令-元素拖拽的實(shí)現(xiàn)代碼

    這篇文章主要介紹了面板拖拽之vue自定義指令,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • Vue項(xiàng)目中如何配置src文件下的@別名

    Vue項(xiàng)目中如何配置src文件下的@別名

    這篇文章主要介紹了Vue項(xiàng)目中如何配置src文件下的@別名問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • vuecli3.0腳手架搭建及不同的打包環(huán)境配置vue.config.js的詳細(xì)過程

    vuecli3.0腳手架搭建及不同的打包環(huán)境配置vue.config.js的詳細(xì)過程

    這篇文章主要介紹了vuecli3.0腳手架搭建及不同的打包環(huán)境配置vue.config.js的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-01-01
  • Vue中兩種生成二維碼(帶logo)并下載方式總結(jié)

    Vue中兩種生成二維碼(帶logo)并下載方式總結(jié)

    與后端生成二維碼相比,前端生成二維碼更具有靈活性,下面這篇文章主要給大家介紹了關(guān)于Vue中兩種生成二維碼(帶logo)并下載的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-03-03
  • vue-resourse將json數(shù)據(jù)輸出實(shí)例

    vue-resourse將json數(shù)據(jù)輸出實(shí)例

    這篇文章主要為大家詳細(xì)介紹了vue-resourse將json數(shù)據(jù)輸出實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • vue路由跳轉(zhuǎn)到新頁面實(shí)現(xiàn)置頂

    vue路由跳轉(zhuǎn)到新頁面實(shí)現(xiàn)置頂

    這篇文章主要介紹了vue路由跳轉(zhuǎn)到新頁面實(shí)現(xiàn)置頂問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 解決vue頁面刷新vuex中state數(shù)據(jù)丟失的問題

    解決vue頁面刷新vuex中state數(shù)據(jù)丟失的問題

    這篇文章介紹了解決vue頁面刷新vuex中state數(shù)據(jù)丟失的問題,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-01-01
  • 一文帶你了解vite對瀏覽器的請求做了什么

    一文帶你了解vite對瀏覽器的請求做了什么

    Vite是一種新型前端構(gòu)建工具,能夠顯著提升前端開發(fā)體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于vite對瀏覽器的請求做了什么的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-12-12

最新評(píng)論