vue2 组件封装 el-input

 

customInput

     index.vue.  // 组件页面

     index.js.    全局注册使用

 

 

index.vue

<template>
  <el-input
    v-bind="$attrs"
    v-on="$listeners"
    :value="value"
    @input="handleInput"
    :placeholder="placeholder"
    :type="type"
    clearable
    :disabled="disabled"
    show-word-limit
  >
    <!-- 透传所有具名插槽和默认插槽 -->
    <template v-for="(slot, name) in $slots" :slot="name">
      <slot :name="name"></slot>
    </template>
  </el-input>
</template>
<script>
export default {
  name: "CustomInput",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    // 去除首尾空格
    autoTrim: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请输入",
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: "text",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否显示字数统计
    showWordLimit: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    // maxlength() {
    //   return this.$attrs.maxlength;
    // }
  },
  mounted(){
  },
  methods: {
    handleInput(value) {
      // 处理自定义逻辑,如 autoTrim
      const finalValue = this.autoTrim ? value.trim() : value;
      // 通过 emit 'input' 事件更新 v-model
      this.$emit("input", finalValue);
      // Vue 3
      // this.$emit("update:modelValue", finalValue);
    },
  },
};
</script>

 

index.js.

import CustomInput from './index.vue';

CustomInput.install = function(Vue) {
  Vue.component(CustomInput.name, CustomInput);
};

export default CustomInput;

 

//main.js  注册全局。vue.use(custominput)

 

页面使用

     <el-form-item label="输入框" prop="name">
        <my-input
          v-model="ruleForm.name"
          placeholder="请输入哈哈"
        > 
           <i slot="suffix" class="el-input__icon el-icon-date"></i>
      </my-input>
      </el-form-item>

image

 

 

关键点解析:
  1. v-bind="$attrs": 这是实现 Props 透传最关键的一步。它会将父组件传递给 MyInput 但没有在 props 中声明的所有属性,全部绑定到内部的 el-input 上。例如 placeholderdisabledmaxlengthtype 等 el-input 支持的原生属性,你都无需在 MyInput 的 props 中重新定义,直接就能用。
  2. v-on="$listeners": 这是事件转发的关键。它会将父组件在 MyInput 上监听的所有事件(如 blurfocuschange),全部转发到内部的 el-input 上。这样,父组件使用 @blur 就和直接使用 el-input 的体验一致。
  3. slot 插槽与原有保持一致

 

posted on 2025-11-14 17:34  Mc525  阅读(0)  评论(0)    收藏  举报

导航