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>

注意:

相关推荐
小北方城市网17 分钟前
JavaScript 实战 —— 实现一个简易的 TodoList(适合前端入门 / 进阶)
开发语言·前端·javascript
是上好佳佳佳呀18 分钟前
【前端(二)】CSS 知识梳理:从编写位置到选择器优先级
前端·css
倾颜43 分钟前
我是怎么把单 Tool Calling 升级成多 Tool Runtime 的
前端·后端·langchain
清汤饺子1 小时前
Superpowers:给 AI 编程 Agent 装上"工程化超能力"
前端·javascript·后端
踩着两条虫1 小时前
AI驱动的Vue3应用开发平台 深入探究(十三):物料系统之区块与页面模板
前端·vue.js·人工智能·架构·系统架构
weixin199701080161 小时前
《得物商品详情页前端性能优化实战》
前端·性能优化
帮我吧智能服务平台1 小时前
装备制造企业售后服务数字化:从成本中心到利润中心背景
java·前端·制造
qq_368019661 小时前
用 react 的react-syntax-highlighter 实现语法高亮、行号与多行错误行高亮
前端·react.js·前端框架
lbh1 小时前
从LLM到Agent的核心概念
前端·openai·ai编程
-Da-2 小时前
【操作系统学习日记】并发编程中的竞态条件与同步机制:互斥锁与信号量
java·服务器·javascript·数据库·系统架构