这里的时间选择表单是我写的一个组件,我想用v-model获取到实时的ref值。
代码:
//父组件<TimePickerModal v-model:value="time" label-text="计划客面时间" />
const time = ref('2024-04-09 15:20:00');
//子组件<template>{{ timeStr }}<div class="row"><div class="label"><span>{{ labelText }}</span><span v-if="isRequired" class="required">*</span></div><div class="detail" style="flex: 1"><ion-inputid="time-trigger"trigger-action="click":value="time"disabled="false"placeholder="请选择":readonly="false"@click="showTimePicker = true"></ion-input></div><van-popup v-model:show="showTimePicker" position="bottom"><van-datetime-pickerv-model="custTime"type="datetime"title="选择时间":min-date="minDate":formatter="formatter"@confirm="Timeconfirm"@cancel="showTimePicker = false"/></van-popup></div>
</template>
<script lang="ts" setup>
import { defineEmits, defineProps, ref, unref, watch } from 'vue';const props = defineProps({value: {type: String,default: '', // 值},
});
const timeStr = ref(unref(props.value) as any);
const time = ref();
// 确认按钮
const Timeconfirm = (value: any) => {time.value = moment(value).format('MMMDo HH:mm'); // 处理成'5月21日 13:20'格式showTimePicker.value = false;timeStr.value = moment(value).format('YYYY-MM-DD HH:mm:ss');
};watch(() => timeStr.value,() => {if (timeStr.value) {time.value = moment(timeStr.value).format('MMMDo HH:mm'); // 处理成'5月21日 13:20'格式}},{immediate: true,}
);
</script>
多余代码已去除,vue中组件传值具有单向数据流的特性,所以想实现双向绑定,则需要在子组件中重新定义一个变量timeStr