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>

注意:

相关推荐
KaMeidebaby7 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl8 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl8 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf8 小时前
Python 异常处理
前端·后端·python
sugar__salt8 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo8 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉8 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
小妖6668 小时前
js 生成随机数技巧 Math.random().toString(36)
javascript·随机数