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>

注意:

相关推荐
RobinDevNotes32 分钟前
从 Electron 到 GPUI,9 个跨平台桌面方案该怎么选
前端·javascript·rust·electron·openresty·前端开发工具
软件技术NINI1 小时前
基于SpringBoot和Vue的新能源汽车销售推荐系统
java·vue.js·spring boot·后端·汽车·毕业设计·毕设
程序员大阳1 小时前
HTML+CSS+JS对话式实战(6)-学生端查看活动功能开发
javascript·css·html·模块·查看学生
jay神2 小时前
基于 YOLOv8 的轴承缺陷检测(Web 版)
前端·人工智能·yolo
jay神2 小时前
基于 YOLOv8 的森林火灾检测系统(Web 版)
前端·yolo
code2cat2 小时前
HTML基础篇之第一张网页:从index.html到浏览器里的任务清单
前端·html
miss2 小时前
AI 改完不敢上线?OpenSpec 规约驱动开发实战
前端·代码规范·前端工程化
招风的黑耳3 小时前
SpringBoot+Vue+MySQL 民宿在线预定平台 完整可运行版(源码+文档)
vue.js·spring boot·mysql
AiMan3 小时前
腾讯ima还是不可以导出左侧所有对话,只能单条导出,方法不对吗
前端
去伪存真3 小时前
并发量一高就装死?Agent 全链路“防猝死”手册
前端·agent