Vue自定义输入组件v-model绑定失效,默认值不显示求助
解决Vue自定义输入组件v-model失效问题
问题根源
你的自定义输入组件没有遵循Vue 2中v-model的实现规范:v-model本质是value属性绑定 + input事件触发的语法糖。你的组件既没有接收父组件传递的value属性来获取初始值,也没有在输入变化时触发input事件同步数据回父组件,而是使用独立的内部数据inputValue,导致双向绑定完全断开。
解决方案
按以下步骤修改组件代码:
- 添加
value属性到props,用于接收父组件v-model传递的初始值和后续更新值 - 将
inputValue改为计算属性,通过get方法读取props的value,set方法触发input事件向父组件传递新值 - 移除data中的
inputValue定义,不再需要独立维护内部数据
修改后的完整代码
<template> <div class="position-relative"> <input :class="[{ 'pe-5': type === 'password' }, 'form-control p-2 rounded-3']" :type="inputType" :id="label ? slugify(label) : null" v-model="inputValue" v-bind="$attrs" /> <CustomButton type="button" transparent class="position-absolute end-0 top-50 translate-y--50" v-if="type === 'password'" @click="togglePasswordVisibility" > <RemixIcon :icon="showPassword ? 'eye-off-line' : 'eye-line'" /> </CustomButton> </div> </template> <script> import RemixIcon from '../components/RemixIcon.vue'; import CustomButton from '../components/CustomButton.vue'; export default { components: { RemixIcon, CustomButton }, props: { type: { type: String, default: 'text', }, label: { type: String, default: '', }, // 新增:接收v-model传递的值 value: { type: [String, Number], default: '' } }, data() { return { showPassword: false, // 移除:不再需要独立的inputValue // inputValue: '', }; }, computed: { inputType() { return this.showPassword ? 'text' : this.type; }, // 新增:用计算属性处理v-model的双向绑定 inputValue: { get() { return this.value; }, set(newValue) { this.$emit('input', newValue); } } }, methods: { togglePasswordVisibility() { this.showPassword = !this.showPassword; }, slugify(str) { return str .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') .replace(/[\s_-]+/g, '-') .replace(/^-+|-+$/g, ''); }, }, }; </script> <style scoped></style>
验证效果
修改完成后,父组件中使用<TextInput type="text" v-model="user_name" />,输入框会正确显示user_name的默认值,输入内容也会实时同步更新父组件的user_name数据。
内容的提问来源于stack exchange,提问作者Gursahb Webcyst
相关产品推荐
相关产品推荐

