打造灵活DateTimePicker日期时间选择器组件:轻松实现时间的独立清除功能

news2024/9/24 20:00:46

element ui中日期和时间选择器(DateTimePicker)是一个常见且重要的组件。它允许用户轻松地选择日期和时间,极大地提升了用户体验。然而,在某些场景下,用户可能需要更细粒度的控制,例如单独清除已选择的时间而保留日期。效果如下图,本文将带领你一步步封装一个DateTimePicker组件,实现时间的独立清除功能。

 实现步骤

1、在components中新建组件dataTimePicker

<template>
  <el-date-picker
    :popper-class="uniqueId"
    style="margin-left: 5px"
    type="datetime"
    v-model="dataTimeValue"
    :placeholder="placeholder"
    @change="changeDateTime"
    @focus="onFocus"
  >
  </el-date-picker>
</template>

1、1给每个组件自定义一个唯一的下拉框class名 

 data() {
    return {
      dataTimeValue: "", // 初始化值
      uniqueId: `date-picker-${Math.random().toString(36).substring(2, 15)}`, // 生成一个唯一的ID
      isAddCloseIcon: false,
    };
  },

1.2 该组件接收两个props

  props: {
    timeValue: {
      type: Date, // 初始展示时间
      required: false,
    },
    placeholder: {
      type: String,
      require: false,
      default: "起始时间",
    },
  },

1.3 在 onFocus事件中,添加清除图标,因为只有当onFocus触发时,下拉框才显示,才能获取到下拉框dom

onFocus() {
      if (this.isAddCloseIcon) return; // 避免重复添加

      this.$nextTick(() => {
        this.timeDiv = document.querySelectorAll(
          `.${this.uniqueId} .el-date-picker__editor-wrap .el-input`,
          this.$el
        )[1];
        this.span = document.createElement("span");
        this.span.innerHTML = `<i class="el-icon-circle-close"></i>`;
        this.span.style.position = "absolute";
        this.span.style.right = "10px";
        this.span.style.cursor = "pointer";
        this.span.style.display = "none"; // 初始时隐藏span
        this.timeDiv.appendChild(this.span);

        // 鼠标移入事件
        this.timeDiv.addEventListener("mouseenter",this.handleMouseenter);

        // 鼠标移出事件
        this.timeDiv.addEventListener("mouseleave", this.handleMouseLeave);

        // 点击事件,清除时间置为00:00:00
        this.span.addEventListener("click", this.clearDateTimeValue);

        this.isAddCloseIcon = true;
      });
    },

1.4  清除时间事件以及鼠标移入显示图标移除隐藏图标:

 clearDateTimeValue() {
      this.dataTimeValue = this.$moment(this.dataTimeValue)
        .startOf("day")
        .toISOString();
    },
    handleMouseLeave() {
        this.span.style.display = "none";
    },
    handleMouseenter() {
        this.span.style.display = "inline";
    }

1.5 时间变化时通知父组件:

changeDateTime(value) {
      this.dataTimeValue = value;
      this.$emit("change", value);
    },

1.6 组件销毁时,移除监听事件:

 beforeDestroy() {
    // 组件销毁前清理事件监听器
    this.span.removeEventListener('click',this.clearDateTimeValue)
    this.timeDiv.removeEventListener('mouseenter',this.handleMouseenter)
    this.timeDiv.removeEventListener('mouseleave',this.handleMouseLeave)
    this.span = null
    this.timeDiv = null
   
  },

完整代码:

dataTimePicker.vue:

<template>
  <el-date-picker
    :popper-class="uniqueId"
    style="margin-left: 5px"
    type="datetime"
    v-model="dataTimeValue"
    :placeholder="placeholder"
    @change="changeDateTime"
    @focus="onFocus"
  >
  </el-date-picker>
</template>
  
  <script>
export default {
  props: {
    timeValue: {
      type: Date,
      required: false,
    },
    placeholder: {
      type: String,
      require: false,
      default: "起始时间",
    },
  },
  data() {
    return {
      dataTimeValue: "", // 初始化值
      uniqueId: `date-picker-${Math.random().toString(36).substring(2, 15)}`, // 生成一个唯一的ID
      isAddCloseIcon: false,
    };
  },
  mounted() {
    this.dataTimeValue = this.timeValue;
  },
  methods: {
    changeDateTime(value) {
      this.dataTimeValue = value;
      this.$emit("change", value);
    },
    onFocus() {
      if (this.isAddCloseIcon) return; // 避免重复添加

      this.$nextTick(() => {
        this.timeDiv = document.querySelectorAll(
          `.${this.uniqueId} .el-date-picker__editor-wrap .el-input`,
          this.$el
        )[1];
        this.span = document.createElement("span");
        this.span.innerHTML = `<i class="el-icon-circle-close"></i>`;
        this.span.style.position = "absolute";
        this.span.style.right = "10px";
        this.span.style.cursor = "pointer";
        this.span.style.display = "none"; // 初始时隐藏span
        this.timeDiv.appendChild(this.span);

        // 鼠标移入事件
        this.timeDiv.addEventListener("mouseenter",this.handleMouseenter);

        // 鼠标移出事件
        this.timeDiv.addEventListener("mouseleave", this.handleMouseLeave);

        this.span.addEventListener("click", this.clearDateTimeValue);

        this.isAddCloseIcon = true;
      });
    },
    clearDateTimeValue() {
      this.dataTimeValue = this.$moment(this.dataTimeValue)
        .startOf("day")
        .toISOString();
    },
    handleMouseLeave() {
        this.span.style.display = "none";
    },
    handleMouseenter() {
        this.span.style.display = "inline";
    }
  },
  beforeDestroy() {
    // 组件销毁前清理事件监听器
    this.span.removeEventListener('click',this.clearDateTimeValue)
    this.timeDiv.removeEventListener('mouseenter',this.handleMouseenter)
    this.timeDiv.removeEventListener('mouseleave',this.handleMouseLeave)
    this.span = null
    this.timeDiv = null
   
  },
};
</script>
  

2、在父组件引入:

<template>
<dateTimePicker :timeValue="startTime"  @change="changeDateTime"></dateTimePicker>
</template>
<script type="text/ecmascript-6">
import dateTimePicker from '@/components/dataTimePicker.vue'
export default {
...,
 methods: {
    changeDateTime(value) {
    console.log('变化',value)
}
}
</script>

3、总结

通过以上方法,我们可以实现在不改变日期的情况下单独清除时间功能,实际上就是在element ui原本的el-date-picker组件上进行改装,增加一个清除按钮并绑定清除事件来实现。实际应用中,你可以根据具体需求进一步扩展和定制这个组件,以满足不同场景下的使用。希望这篇文章能对你有所帮助!

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2161291.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

4款思维导图在线工具,新手速来!

想要工作更顺畅&#xff0c;办公软件少不了&#xff01;让咱们工作生活变得更加井井有条的小能手——思维导图软件。没错&#xff0c;就是那些能让你在头脑风暴、项目规划、会议记录时&#xff0c;思路瞬间清晰&#xff0c;逻辑一目了然的神奇工具。我亲身体验过的四款款热门软…

Web端云剪辑解决方案,提供前端产品源码

美摄科技作为业界领先的视频技术服务商&#xff0c;匠心打造Web端云剪辑解决方案&#xff0c;以前沿技术赋能企业用户&#xff0c;开启视频创作与编辑的新纪元。 【云端赋能&#xff0c;重塑剪辑体验】 美摄科技的Web端云剪辑解决方案&#xff0c;颠覆了传统视频编辑的局限&a…

Excel VLOOKUP函数怎么用?vlookup函数的使用方法及案例

大家好&#xff0c;这里是效率办公指南&#xff01; &#x1f50e; 在Excel的世界里&#xff0c;VLOOKUP函数无疑是查询和数据分析中的明星。无论是从庞大的数据表中提取特定信息&#xff0c;还是进行数据的快速匹配&#xff0c;VLOOKUP都能大显身手。今天&#xff0c;我们将深…

多机器学习模型学习

特征处理 import os import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedShuffleSplit from sklearn.impute import SimpleImputer from sklearn.pipeline import FeatureUnion fr…

行业副教授亲授,好评如潮丨合成孔径雷达干涉测量InSAR数据处理、地形三维重建、形变信息提取、监测等技能,助力精准决策!

目录 第一章 InSAR技术应用现状分析及其发展 第二章 InSAR原理、技术方法讲解 第三章 数据处理环境建立与软件熟悉 第四章 SAR影像数据获取、DEM数据获取 InSAR数据前处理技术 第五章 InSAR地形三维重建 第六章 DInSAR形变信息提取 第七章 时序InSAR技术形变速率与形变时…

【C++】检测TCP链接超时——时间轮组件设计

目录 引言 时间轮思想 设计的核心思路 完整代码 组件接口 个人主页&#xff1a;东洛的克莱斯韦克-CSDN博客 引言 对于高并发的服务器来说&#xff0c;链接是一种比较珍贵的资源&#xff0c;对不活跃的链接应该及时释放。判断连接是否活跃的策略是——在给定的时间内&#…

04 面部表情识别:Pytorch实现表情识别-表情数据集训练代码

总目录:人脸检测与表情分类 https://blog.csdn.net/whiffeyf/category_12793480.html 目录 0 相关资料1 面部表情识数据集2 模型下载3 训练0 相关资料 面部表情识别2:Pytorch实现表情识别(含表情识别数据集和训练代码):https://blog.csdn.net/guyuealian/article/details/1…

017_FEA_CSG_in_Matlab新的统一有限元分析工作流之2D几何

Matlab新的统一有限元分析工作流 从2023a开始&#xff0c;Matlab提供了一个统一有限元分析工作流&#xff08;UFEAW&#xff0c;unified finite element analysis workflow&#xff09;。 这个新的工作留提供一个统一的接口来求解三类问题&#xff0c;并且可以用同一套数据随…

828华为云征文 | 云服务器Flexus X实例,Docker集成搭建搭建Flink

828华为云征文 | 云服务器Flexus X实例&#xff0c;Docker集成搭建搭建Flink Apache Flink是一个分布式大数据计算引擎&#xff0c;专为处理无界和有界数据流上的有状态计算而设计&#xff0c;以其高吞吐量、低延迟和高性能在实时流处理和批量计算领域脱颖而出&#xff0c;Flin…

Vue2电商项目(四) Detail模块

文章目录 一、配置Detail路由1. 将Detail组件配置为路由组件2. 将路由配置文件拆分3. 声明式导航跳转到Detail跳转时存在的问题&#xff1a;页面滚动条还在下边 二、配置API及vuex三、放大镜及下方轮播图1. Detail组件传递放大镜数据2. 读取vuex数据的经典错误undefined3. 放大…

个人如何做量化?我想进行量化交易需要哪些条件?QMT/PTrade量化软件?

个人如何做量化&#xff1f;我想进行量化交易需要哪些条件&#xff1f;QMT&#xff0c;PTrade量化软件&#xff1f; 量化交易策略是一种基于数学模型和统计分析的交易方法&#xff0c;通过计算机程序自动执行交易指令&#xff0c;以实现稳定、可持续的收益。这种策略的核心思想…

【研赛E题成品论文】24华为杯数学建模研赛E题成品论文+可运行代码丨免费分享

2024华为杯研究生数学建模竞赛E题成品论文已出&#xff01; E题 高速公路应急车道紧急启用模型 一、问题一模型建立与求解 1.1 问题一求解思路 赛题要求我们基于四个观测点的视频数据&#xff0c;提取交通流参数并分析这些参数随时间的变化规律。交通流参数包括&#xff1a;…

【秋招笔试题】多多排序

解法&#xff1a;简单语法题 package com.sky;import java.util.*;public class Test1 {public static void main(String[] args) {Scanner sc new Scanner(System.in);int N sc.nextInt();int M sc.nextInt();List<String> words new ArrayList<>(N);for (in…

[系统设计总结] - Proximity Service算法介绍

问题描述 Proximity Service广泛应用于各种地图相关的服务中比如外卖&#xff0c;大众点评&#xff0c;Uber打车&#xff0c;Google地图中&#xff0c;其中比较关键的是我们根据用户的位置来快速找到附近的餐厅&#xff0c;司机&#xff0c;外卖员也就是就近查询算法。 主流的…

再论单源最短路径-SPFA

之前只是背了SPFA的算法模板&#xff0c;但是没有真正理解其中含义。这里复习时再次进行理解。 首先&#xff0c;正常的单源最短路径都会由下面的一个结构来维护“距离”&#xff0c;这个结构可以用一个数字dist[N]来描述&#xff0c;其中下标为顶点编号&#xff0c;值为“暂时…

期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟

在 AI 程序员的帮助下&#xff0c;一个几乎没有专业编程经验的初中生&#xff0c;在人头攒动的展台上从零开始&#xff0c;两分钟就做出了一个倒计时网页。 他需要做的&#xff0c;只是输入包含几句话的提示词。数秒钟后&#xff0c;大模型就生成了代码&#xff0c;还列出了环…

Redis6.0.9配置redis集群

写在前面 最近在完成暑期大作业&#xff0c;期间要将项目部署在云服务器上&#xff0c;其中需要进行缓存的配置&#xff0c;决定使用Redis&#xff0c;为了使系统更加健壮&#xff0c;选择配置Redis-Cluster。由于服务器资源有限&#xff0c;在一台服务器上运行6个Redis Instan…

Springboot-多数据源

文章目录 一、架构二、实现过程2.1 第一步&#xff1a;引入依赖pom2.2 第二步&#xff1a;创建application.yml配置2.3 第三步&#xff1a;创建架构的文件夹MybatisPlusConfigFirstDataSourceConfigSecondDataSourceConfig 实现功能&#xff0c;在不同的文件夹使用不同的库 一、…

【软件测试】金九银十,APP面试题经验分享

Web 端测试和 App 端测试有何不同? ① 系统架构方面 Web 项目&#xff0c;b/s架构&#xff0c;基于浏览器的&#xff1b;Web 测试只要更新了服务器端&#xff0c;客户端就会同步会更新&#xff1b; App 项目&#xff0c;c/s架构的&#xff0c;必须要有客户端&#xff1b;App…

基于Ambari搭建大数据分析平台(30分钟速成)全网最全最详细的Ambari搭建大数据分析平台:

全网最全最详细的Ambari搭建大数据分析平台&#xff1a; 方法一适合详细自己独立安装&#xff0c;方法二超级详细具体&#xff0c;是根据方法一搭建成功的&#xff0c;方法三是另外的方法&#xff0c;安装包有不同&#xff0c;实践也能安装成功。 方法一&#xff1a; 1.搭建安…