
本文详解如何在 Vue 3 自定义 组件中正确支持 v-model,包括 v-model 的底层原理、双向绑定的实现方式(modelValue prop + update:modelValue 事件),以及密码切换、ID 生成等增强功能的兼容性处理。
本文详解如何在 vue 3 自定义 `
在 Vue 3 中,v-model 不再是语法糖的简单替换,而是基于 modelValue prop 和 update:modelValue 事件的标准化约定。你当前的组件未遵循该约定,因此 v-model="user_name" 无法将初始值同步到 ,也无法响应用户输入更新父组件数据。
要使自定义输入组件真正支持 v-model,需做三处关键修改:
✅ 1. 接收 modelValue Prop 并绑定到
将 v-model="inputValue" 替换为 :value="modelValue",并监听原生 input 事件触发 update:modelValue:
<template><div class="position-relative">
<input :class="[{ 'pe-5': type === 'password' }, 'form-control p-2 rounded-3']" :type="inputType" :id="label ? slugify(label) : null" :value="modelValue" v-model>
@input="$emit('update:modelValue', $event.target.value)" <!-- ✅ 触发标准事件 -->
v-bind="$attrs"
/>
<custombutton type="button" transparent class="position-absolute end-0 top-50 translate-y--50" v-if="type === 'password'"><remixicon :icon="showPassword ? 'eye-off-line' : 'eye-line'"></remixicon></custombutton>
</div>
</template>
✅ 2. 声明 modelValue prop 并移除冗余 data
删除 data() 中的 inputValue,改用 props.modelValue 作为输入值来源:
export default {
components: { RemixIcon, CustomButton },
props: {
type: {
type: String,
default: 'text'
},
label: {
type: String,
default: ''
},
modelValue: { // ✅ 显式声明 modelValue prop
type: [String, Number], // 支持字符串和数字类型
default: ''
}
},
data() {
return {
showPassword: false
};
},
computed: {
inputType() {
return this.showPassword ? 'text' : this.type;
}
},
methods: {
togglePasswordVisibility() {
this.showPassword = !this.showPassword;
},
slugify(str) {
return str
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
}
}
};
✅ 3. 父组件使用方式保持不变(但更健壮)
现在可直接使用 v-model,且默认值、双向更新均正常工作:
<!-- 父组件 --> <textinput type="text" label="用户名" v-model="user_name"></textinput><!-- user_name 初始值(如 'admin')会自动显示在 input 中 -->
⚠️ 注意事项
- 不要同时使用 v-model 和 :value / @input,否则会冲突;
- 若需支持其他 v-model 修饰符(如 .lazy, .number),应监听 change 事件或配合 @blur 处理;
- v-bind="$attrs" 已自动透传 id、placeholder、disabled 等原生属性,无需额外处理;
- Vue 3.4+ 支持 defineModel() 宏(实验性),可进一步简化写法,但当前兼容性方案更稳妥。
至此,你的
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











