VUE篇之自定义组件使用v-model

子组件:

html 复制代码
<template>
  <div>
    <!-- 这里以 el-time-select 为例,实际可以是任何表单控件 -->
    <el-time-select
      v-model="innerValue.time"
      :picker-options="timeOptions"
      @change="handleTimeChange"
      placeholder="选择时间"
    />
  </div>
</template>

<script>
export default {
  props: {
    value: {  // 必须使用 value 作为 prop 名
      type: Object,
      default: () => ({
        time: '',
        // 其他可能的属性
      }),
      required: true
    }
  },
  data() {
    return {
      timeOptions: {
        start: '08:30',
        step: '00:15',
        end: '18:30'
      },
      // 创建内部副本以避免直接修改 prop
      innerValue: JSON.parse(JSON.stringify(this.value))
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.innerValue = JSON.parse(JSON.stringify(newVal))
      },
      deep: true
    }
  },
  methods: {
    handleTimeChange(newTime) {
      const newValue = { ...this.internalValue, time: newTime };
      this.internalValue = newValue;
      // 触发 input 事件以更新 v-model
      this.$emit('input', newValue)
    }
  }
}
</script>

父组件:

html 复制代码
<template>
  <div>
    <my-component v-model="formData" />
    <p>当前时间: {{ formData.time }}</p>
    <pre>{{ formData }}</pre>
  </div>
</template>

<script>
import MyComponent from './time.vue'

export default {
  components: {
    MyComponent
  },
  data() {
    return {
      formData: {
        time: '09:00',
        // 可以包含其他属性
        meta: 'additional data'
      }
    }
  }
}
</script>

注意:

相关推荐
夜焱辰6 小时前
浏览器端 Agent 的文件版本管理:不用 Git,基于 OPFS + SQLite 自己造了一个
前端·人工智能
梦想的颜色6 小时前
TypeScript 完全指南(下):从类型体操到生产级配置
前端·javascript·typescript
Hi~晴天大圣8 小时前
npm使用介绍
前端·npm·node.js
888CC++8 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
喵个咪9 小时前
基于 Taro 的 Headless CMS 多端前端架构:技术解析与二次开发导引
前端·react.js·taro
狂炫冰美式9 小时前
你还在古法PPT吗,试试HTML呢?免费编辑导出工具给 xdm 放这了
前端·后端·github
万少9 小时前
未来组织的分水岭不是员工数量,而是人才密度
前端·后端·面试
任磊abc9 小时前
nextjs16配置eslint+prettier
前端·eslint·nextjs·prettier
x***r15110 小时前
Another-Redis-Desktop-Manager.1.3.7安装步骤详解(附Redis可视化连接与Key管理教程)
前端·bootstrap·html
Captaincc10 小时前
你真的知道自己把 AI 用在了哪里吗?这是 Vibe Usage 想回答的问题
前端·vibecoding