Element-plus DatePicker日期选择器无法设置绑定时间为new Date()当前时间

发布时间 2023-08-25 10:50:41作者: Mr、ZZZ

点击查看源码

 <template>
  <div class="demo-date-picker">
    <div class="block">
      <span class="demonstration">Use value-format</span>
      <div class="demonstration">Value:{{ value2 }}</div>
      <el-date-picker
        v-model="value2"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

const value2 = ref(new Date())
</script>

此问题为设置了 value-format="YYYY-MM-DD" 之后v-model绑定的new Date()格式与设置的value-format格式不匹配导致

 
可以利用Element-plus组件库默认支持 dayjs 将绑定的时间设置为value-format指定的格式即可

点击查看源码

 <template>
  <div class="demo-date-picker">
    <div class="block">
      <span class="demonstration">Use value-format</span>
      <div class="demonstration">Value:{{ value2 }}</div>
      <el-date-picker
        v-model="value2"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { dayjs } from 'element-plus';
import { ref } from 'vue'

const value2 = ref(dayjs().format('YYYY-MM-DD'))
</script>

 

Element-plus组件库默认支持 dayjs 进行日期时间处理,所以可以直接导入使用,相关 Date Picker (opens new window)组件介绍。