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>

注意:

相关推荐
hunterandroid4 小时前
Compose 状态管理:remember、rememberSaveable 与状态提升
前端
星栈4 小时前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架
晴虹4 小时前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js
代码搬运媛4 小时前
Claude 全栈开发专用 Rules 配置
前端
PedroQue994 小时前
uni-router v1.7.0重磅更新:守卫重定向自由掌控
前端·uni-app
Forever7_4 小时前
尤雨溪转发:Vue-tui 0.1 发布!Vue 终于杀进终端!
vue.js
逸铭4 小时前
Day 4:登录与 Token——桌面端怎么存密钥
前端·客户端
默_笙4 小时前
🍞 我用 CSS 画了一个会转的 3D 立方体,同事以为我学了 Three.js(这节课真的很神奇,我很喜欢)
javascript
dkbnull4 小时前
Vue 虚拟 DOM Diff 算法与 key 机制原理
vue.js
溯朢4 小时前
TokUI 流式渲染的 SSE 全链路拆解
前端