二次封装ui组件,如何做到属性,作用域插槽以及 实例方法的穿透使用

发布时间 2023-04-06 15:24:52作者: 10后程序员劝退师

A页面: 在使用二次封装的组件

<MyInput  ref='inputRef' v-model='data' placeholder='xxxx'>

  <template #prepend>
      ......
  </template>

  <template #append>
      ......
  </template>
 
 
</MyInput>

onMounted(() => {
  inputRef.value.focus()  //外部便可以调用内部组件的方法
})
MyInput.vue 二次封装
<template>
  <div class='自定义二次封装的内容'>
// $attrs 绑定到组件的所有属性 <el-input ref='inp' v-bind='$attrs'>
//动态获取插槽和 作用域 <template v-for='(value, name) in $slots' #[name] = 'slotData'> <slot :name=name v-bind='slotData || {}'></slot> </template> </el-input> </div> </template> created(){ const entries = object.entries(this.$refs.inp)
//将 组件的下的方法 同步到该组件的实例上
for( const [key, value] of entries ){ this[key] = value } }