ts写法及ui组件封装记录之el-input
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                
import { App, defineComponent, PropType, ref } from 'vue';
import { ElInput } from 'element-plus';
 
// 定义组件Props接口
interface Props {
  modelValue: string;
  placeholder?: string;
  clearable?: boolean;
}
 
// 定义组件Emits接口
interface Emits {
  (e: 'update:modelValue', value: string): void;
}
 
// 定义组件
export default defineComponent({
  name: 'ElInputWrap',
  components: { ElInput },
  props: {
    modelValue: {
      type: String as PropType<string>,
      default: '',
    },
    placeholder: {
      type: String as PropType<string>,
      default: '请输入内容',
    },
    clearable: {
      type: Boolean as PropType<boolean>,
      default: true,
    },
  },
  emits: ['update:modelValue'],
  setup(props: Props, { emit }: { emit: (event: Emits) => void }) {
    // 使用ref创建响应式数据
    const inputValue = ref(props.modelValue);
 
    // 监听inputValue变化,并通过emit更新父组件的modelValue
    watch(inputValue, (newValue) => {
      emit('update:modelValue', newValue);
    });
 
    return {
      inputValue,
    };
  },
});这段代码定义了一个封装了ElInput组件的Vue 3组件,它使用TypeScript并通过组件Props和Emits接口来规范化交互。它还展示了如何使用Vue 3的ref来创建响应式数据,并通过watch来响应数据的变化。这是一个简单而又有效的封装示例,对于开发者学习如何封装基于Element Plus组件的Vue UI库是很有帮助的。
评论已关闭