组件的封装要素

53 阅读1分钟
  • $attrs 透传父组件传入的 属性 + 事件
  • $slots 透传父组件传入的 插槽

组件的二次封装示例[基于Vue3.x + elementUI]

<template>
  <!-- $attrs 透传父组件传入的 属性 + 事件 -->
  <el-input
    ref="elInputRef"
    v-bind="$attrs"
  >
    <!-- $slots 透传父组件传入的 插槽  v-bind="data"是将el-input组件的数据透传给父组件-->
    <template
      v-for="(_, key) in $slots"
      :key="key"
      #[key]="data"
    >
      <slot
        :name="key"
        v-bind="data"
      />
    </template>
  </el-input>
</template>

<script setup>
import { ref, useAttrs, useSlots } from 'vue'

const attrs = useAttrs()
console.log('attrs', attrs);
const slots = useSlots()
console.log('slots', slots);

const elInputRef = ref("elInputRef")
const getElInputRef = ()=>{ // 获取 el-input 组件实例
  return elInputRef.value
}

defineExpose({
  getElInputRef
})
</script>

使用

<template>
  <MyInput ref="myInputRef" v-model="input" @input="onInput">
    <template #prepend>
      Http://
    </template>
    <template #append>
      .com
    </template>
  </MyInput>
  <el-button type="primary" @click="onReset">
    reset
  </el-button>
</template>

<script setup>
import { ref, computed } from 'vue'
import MyInput from './Child.vue'

const input = ref("")
const onInput = (val) => {
  console.log('onInput---val', val);
}

const myInputRef = ref(null)
const elInputRef = computed(() => myInputRef.value.getElInputRef())
const onReset = () => {
  elInputRef.value.clear()
}
</script>