封装 Element Plus - Input 组件

52 阅读2分钟

封装 Element Plus - Input 组件

有关 vue3 封装 element-plus 的 input 组件

elementUI是一个vue.js的ui框架, 在做后台管理系统等方面非常出色,然而面对重复的后台管理系统,大量重复的代码, 这里我们将使用elemnt ui做二次封装,以扩展element ui的属性 来简化代码.

封装第三方组件有几个主要好处:

  1. ​统一接口​​:可以在项目中保持一致的 API
  2. ​简化使用​​:隐藏复杂的配置,提供更简单的接口
  3. ​增强功能​​:添加项目特有的功能或行为
  4. ​便于替换​​:如果未来需要更换组件库,只需修改封装层

TS

<template>
  <view class="container">
    <MyInput ref="inputRef" v-model="msg"></MyInput>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
  import MyInput from "@/components/MyInput.vue";

  const msg = ref('哈哈哈🤣')
  const inputRef = ref()

  setTimeout(() => {
    console.log(inputRef.value)
    inputRef.value.clear()
  }, 1000);
</script>
<template>
    <component :is="h(ElInput, {...$attrs, ...props, ref: changeRef}, $slots)"></component>
</template>
  
<script lang="ts" setup>
import { ElInput, type InputProps} from 'element-plus'
import { h, getCurrentInstance } from 'vue';

const props = defineProps<Partial<InputProps>>()
const vm = getCurrentInstance()

function changeRef(inputInstance) {
  console.log(inputInstance)
  vm.exposeProxy = vm.exposed = inputInstance || {}
}
</script>

JS

<template>
  <view class="container">
    <MyInput ref="inputRef" v-model="msg">
      <template #prepend>before</template>
      <template #append>after</template>
    </MyInput>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import MyInput from "@/components/MyInput.vue";

const msg = ref('哈哈哈🤣')
const inputRef = ref(null)

setTimeout(() => {
  console.log(inputRef.value)
}, 1000);
</script>
<template>
  <el-input ref="elInput" v-bind="$attrs">
    <template v-for="(_, name) in $slots" #[name]="scopedData">
      <slot :name="name" v-bind="scopedData"></slot>
    </template>
  </el-input>
</template>

<script>
  export default {
    mounted() {
      console.log('this.$attrs', this.$attrs)
      console.log('this.$slots', this.$slots)
      console.log('this.$refs', this.$refs)
      for (const key in this.$refs.elInput) {
        this[key] = this.$refs.elInput[key]
      }
    }
  }
</script>

特点

  1. ​模板方式​​:使用常规模板语法
  2. ​透传属性和插槽​​:通过 v-bind="$attrs"和 v-for插槽实现
  3. ​引用代理​​:在 mounted 钩子中将 ElInput 的方法代理到封装组件

优点

  • 实现简单直观
  • 完全透传所有属性和插槽
  • 易于理解和维护

缺点

  • 缺乏类型检查
  • 引用代理方式可能不够健壮

使用示例

两种封装方式都支持类似的使用方式:

<template>
  <view class="container">
    <MyInput ref="inputRef" v-model="msg">
      <template #prepend>before</template>
      <template #append>after</template>
    </MyInput>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import MyInput from "@/components/MyInput.vue";

const msg = ref('哈哈哈🤣')
const inputRef = ref(null)

setTimeout(() => {
  console.log(inputRef.value)
}, 1000);
</script>

封装第三方组件是 Vue 项目中的常见需求,Element Plus 的 Input 组件提供了丰富的功能,通过合理的封装可以使其更好地融入项目架构。TypeScript 版本提供了更好的类型安全,而 JavaScript 版本则更简单直接。开发者应根据项目实际情况选择合适的封装方式。