vue 高阶组件(HOC)

7 篇文章 0 订阅

1概念

一个函数接受一个组件为参数,返回一个包装后的组件(对象)

高阶组件:接受一个组件并返回一个组件(对象),这个组件具有原组件的功能,并拥有了新自定义的功能。

Vue 的世界里,高阶组件就是 fn(object) -> 新的object

 

高阶组件应该是有以下特征:

高阶组件应该是无副作用的纯函数,且不应该修改原组件,即原组件不能有变动
高阶组件不关心你传递的数据(props)是什么,并且新生成组件不关心数据来源
高阶组件接收到的 props 应该透传给被包装组件即直接将原组件prop传给包装组件
高阶组件完全可以添加、删除、修改 props

智能组件和木偶组件

木偶 组件: 就像一个牵线木偶一样,只根据外部传入的 props 去渲染相应的视图,而不管这个数据是从哪里来的。

智能 组件: 一般包在 木偶 组件的外部,通过请求等方式获取到数据,传入给 木偶 组件,控制它的渲染。

一般来说,它们的结构关系是这样的:

<智能组件>
  <木偶组件 />
//使用render
export default {
  name: 'renderTest',
  data() {},
  render: (createElement) => {
    return createElement(tag, data, context)
  },
  props: {},
  methods: {},
  created () {}
  ...
}






// 使用template属性 也可使用<script type="text/x-template" id="xxx"> 标签 或 <template id="xxx"> 形式
 Vue.component('test-component',{
    template:`<h1>this is test,{{test}}</h1>`,
    data(){
     return{
       test:"hello test"
       }
      }
  })

// 使用template 模版
<template >
  <h1>Title</h1>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</template>


export default {
    data:{},
    ....
}

 

关于render 写法的注意点

vm.$attrs

包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

vm.$listeners

包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

 

看一个例子

有一个详情页面,一个图片以及一些文本信息,其模板结构为

<template>
    <div>
        <img src="https://avatars.githubusercontent.com/u/71475868?s=40&amp;u=8e47a668961f89a6389d9775cffdabddfda76e8c&amp;v=4" />
        <div> 用户名称 </div>
    </div>
</template>

其中图片、用户名称数据,通过 id 请求获取数据

<template>
    <div>
        <smart-avatar :id="'testId'" :src="https://avatars.githubusercontent.com/u/71475868?s=40&amp;u=8e47a668961f89a6389d9775cffdabddfda76e8c&amp;v=4"/>
    </div>   
</template>//模拟请求
function fakerRequest(id){
    return new Promise(resovle=> {
        setTimeout(()=>{
            const username = '测试';
            const url = 'https://forgiveforever.github.io/img/head.jpg';
            resovle({url, username })
       },500)
    })
}const Item = {
    props: ['url','username'],
    template:`<div><img :src="url" style="max-width: 200px"/> <span>{{username}}</span></div>`   
}




export function withAvatarURL (InnerComponent) {
    return {
      props: ['id'],
      inheritAttrs: false, // 2.4 only
      data () {
        return {
            username: '',
            url: ''
        }
      },
      created () {
        fakerRequest(this.id).then(res => {
            this.username = res.username;
            this.url = res.url;
        })
      },
      render (h) {
        return h(InnerComponent, {
          attrs: this.$attrs,
          props: {
            url: this.url,
            username: this.username
          }
        })
      }
    }
  }const SmartAvatar = withAvatarURL(Item)new Vue({
  el: '#app',
  components: { SmartAvatar }
})

如上代码中,我们用一个高阶组件函数withAvatarURL去接受了我们原始组件Item,其中

  • Item组件只负责将接收到的url赋给img标签以及现实对应用户名称
  • withAvatarURL负责加工我们的原始组件,将该类型组件的公用方法抽离出来,再赋予给原始组件

 

具体🌰

WithConsole就是一个高阶组件,它接收一个组件作为参数:WrappedComponent,并返回一个新的组件。在新的组件定义中,我们将WrappedComponent 注册为wrapped组件,并在 template中将其渲染出来,同时添加 mounted钩子,打印 I have already mounted。

以上就完成了与mixins同样的功能,不过这一次我们采用的是高阶组件,所以是非侵入式的,我们没有修改原组件(WrappedComponent),而是在新组件中渲染了原组件,并且没有对原组件做任何修改。

并且这里大家要注意 listenersattrs:这么做是必须的,这就等价于在 React 中透传 props:否则在使用高阶组件的时候,被包装组件(WrappedComponent)接收不到props和 事件。(v-model 除外)

listeners 不会被劫持

// hoc.js
export default function WithConsole (WrappedComponent) {
  return {
    template: '<wrapped v-on="$listeners" v-bind="$attrs"/>',
    components: {
      wrapped: WrappedComponent
    },
    mounted () {
      console.log('I have already mounted')
    }
  }
}

注意 template 选项只有在完整版的 Vue 中可以使用,在运行时版本中是不能使用的,所以最起码我们应该使用渲染函数(render)替代模板(template),如下:

//  render 方式
export function WithConsoleRender (WrappedComponent) {
    return {
      mounted () {
        console.log('I have already mounted')
      },
    //   render (h) {
    //     return h(WrappedComponent)
    //   }
      render (h) {
        return h(WrappedComponent, {
          on: this.$listeners,
          attrs: this.$attrs,
        })
      }
    }
}

注意如何写defaultSlot slot

function WithConsole (WrappedComponent) {
    return {
      mounted () {
        console.log('I have already mounted')
      },
      props: WrappedComponent.props,
      render (h) {
        const slots = Object.keys(this.$slots)
          .reduce((arr, key) => arr.concat(this.$slots[key]), [])
          .map(vnode => {
            vnode.context = this._self 
            return vnode
          })
   
        return h(WrappedComponent, {
          on: this.$listeners,
          props: this.$props,
          // 透传 scopedSlots
          scopedSlots: this.$scopedSlots,
          attrs: this.$attrs
        }, slots)
      }
    }
  }

应用场景

1.面向切面(例如在生命周期里进行一些事儿)或者扩展原有组件功能 (例如 renderToBody)

 

父子组件生命周期 加载顺序

父子组件的执行顺序:

加载渲染过程:

beforeCreate->created->beforeMount->beforeCreate->created->beforeMount->mounted->mounted

子组件更新过程:

beforeUpdate->beforeUpdate->updated->updated

父组件更新过程:

beforeUpdate->updated

销毁过程:

beforeDestroy->beforeDestroy->destroyed->destroyed

 

 

export function AddToBody (WrappedComponent) {
    return {
        props: {
            appendToTaget: {
                type: String,
                default: ''
            },
            ...WrappedComponent.props
        },
        mounted(){
            this.appendToEle();
        },
        methods: {
            appendToEle(){
                const id = this.appendToTaget;
                if(!this.appendToTaget) return;
                const target = document.getElementById(id);
                if (target) {
                    target.appendChild(this.$el);
                }
            }
        },
        render (h) {
            const slots = Object.keys(this.$slots)
            .reduce((arr, key) => arr.concat(this.$slots[key]), [])
            .map(vnode => {
                vnode.context = this._self
                return vnode
            })
     
            return h(WrappedComponent, {
            on: this.$listeners,
            props: this.$props,
            // 透传 scopedSlots
            scopedSlots: this.$scopedSlots,
            attrs: this.$attrs
            }, slots)
        }
    }
  }

2.数据和渲染分离(比如一些查看页面,进入页面之前会请求数据,请求之前加上loading, 请求失败提示)

/// HOC 函数
export function HOCLook (WrappedComponent, xhrFn) {
    return {
        props: {
        },
        data(){
            return {
                res: {}
            }
        },
        created(){
           this.getData();
        },
        methods: {
            async getData(){
                const res = await xhrFn();
                this.res = res;
            }
        },
        render (h) {
            const res = this.res;


            if(res.success === undefined){
                return h('div',['请求中']);
            }
            if(res.code == 0){
                const slots = Object.keys(this.$slots)
                .reduce((arr, key) => arr.concat(this.$slots[key]), [])
                .map(vnode => {
                    vnode.context = this._self
                    return vnode
                })
         
                return h(WrappedComponent, {
                on: this.$listeners,
                props: {
                    res: this.res
                },
                // 透传 scopedSlots
                scopedSlots: this.$scopedSlots,
                attrs: this.$attrs
                }, slots)
            }else {
                return h('div',['请求失败']);
            }


        }
    }
  }










<template>
    <Custom></Custom>
</template>


<script>
import { HOCLook } from './hoc.js'
import lookVue from './comps/look.vue';
const api = () => {
    return new Promise((res)=>{
        setTimeout(()=>{
            if(Date.now() % 2 === 0){
                    res({code: 0, msg: '成功', success: true})
                }else {
                    res({code: -1, msg: '请求失败',success: false})
                }
            })
        }, 4000)
}
const Custom = HOCLook(lookVue,api);
export default {
    name: 'hoc-dialog',
    components: {Custom}
}
</script>
组件的二次封装
<template>
    <ui-pager class="custom-pager" v-on="$listeners" v-bind="$attrs"></ui-pager>
</template>
<script>
export default {
    name: 'custom-pager',
    props: {
        appendToTaget: {
            type: String,
            default: ''
        }
    },
    mounted(){
        this.appendToEle();
    },
    methods: {
        appendToEle(){
            const id = this.appendToTaget;
            if(!this.appendToTaget) return;
            const target = document.getElementById(id);
            if (target) {
                target.appendChild(this.$el);
            }
        }
    }
}

3.vue 应用有多个页面(router),需要权限控制

总结就是

运用高阶组件,能够保留原有组件的所有特性下创造一个新的组件,使得原有组件的重用性更高。

 

高阶函数和mixin的选择


高阶组件有以下优势:

重用性。因为minxin对原组件具有侵入性,这会导致原来组件的可重用性降低,而高阶组件不会,高阶组件对原组件只是一个调用关系,并没有修改原来组件任何内容。
可测试性。因为高阶组件只是一个嵌套关系,在组件测试的时候,可以单独的测试原始组件和高阶组件。
层级问题。高阶组件也有他的弊端,如果你高阶组件嵌套层级太深,会导致出错的时候调试困难的问题,所以到底使用高阶组件和minxin需要看实际场景。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值