vue3自定义指令显示(刚刚 分钟前 小时前...)

       例如实现聊天评论我们可以看见当前评论下的评论日期距离当前日期的时间范围,然人在观看评论的时候可以一眼就知道当前的评论距离此时有多久,可以一目了然.

// const tool = require("@/utils/tool.js");
import * as tool from "@/utils/tool.js";
var Time = {
  //获取当前时间戳
  getUnix: function () {
    var date = new Date();
    return date.getTime();
  },
  //获取今天0点0分0秒的时间戳
  getTodayUnix: function () {
    var date = new Date();
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date.getTime();
  },
  //获取今年1月1日0点0秒的时间戳
  getYearUnix: function () {
    var date = new Date();
    date.setMonth(0);
    date.setDate(1);
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date.getTime();
  },
  //获取标准年月日
  getLastDate: function (time: any) {
    var date = new Date(time);
    var month =
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + day;
  },
  //转换时间
  getFormateTime: function (timestamp: any) {
    timestamp = new Date(timestamp);
    var now = this.getUnix();
    var today = this.getTodayUnix();
    //var year = this.getYearUnix();
    var timer = (now - timestamp) / 1000;
    var tip = "";

    if (timer <= 0) {
      tip = "刚刚";
    } else if (Math.floor(timer / 60) <= 0) {
      tip = "刚刚";
    } else if (timer < 3600) {
      tip = Math.floor(timer / 60) + "分钟前";
    } else if (timer >= 3600 && timestamp - today >= 0) {
      tip = Math.floor(timer / 3600) + "小时前";
    } else if (timer / 86400 <= 31) {
      tip = Math.ceil(timer / 86400) + "天前";
    } else {
      tip = this.getLastDate(timestamp);
    }
    return tip;
  },
};

export default (el: any, binding: any) => {
  let { value, modifiers } = binding;
  if (!value) {
    return false;
  }
  if (value.toString().length == 10) {
    value = value * 1000;
  }
  if (modifiers.tip) {
    el.innerHTML = Time.getFormateTime(value);
    el.__timeout__ = setInterval(() => {
      el.innerHTML = Time.getFormateTime(value);
    }, 60000);
  } else {
    const format = el.getAttribute("format") || undefined;
    el.innerHTML = (tool as any).default.dateFormat(value, format);
  }
};

import time from "@/directives/time";

app.directive("time", time);

config.js如下:

        

tool.js:

/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: hongqiang
 * @LastEditTime: 2024-05-07 16:07:21
 */

import CryptoJS from "crypto-js";
import sysConfig from "@/config";

const tool = {};

/* localStorage */
tool.data = {
  set(key, data, datetime = 0) {
    //加密
    if (sysConfig.LS_ENCRYPTION == "AES") {
      data = tool.crypto.AES.encrypt(
        JSON.stringify(data),
        sysConfig.LS_ENCRYPTION_key
      );
    }
    let cacheValue = {
      content: data,
      datetime:
        parseInt(datetime) === 0
          ? 0
          : new Date().getTime() + parseInt(datetime) * 1000,
    };
    return localStorage.setItem(key, JSON.stringify(cacheValue));
  },
  get(key) {
    try {
      const value = JSON.parse(localStorage.getItem(key));
      if (value) {
        let nowTime = new Date().getTime();
        if (nowTime > value.datetime && value.datetime != 0) {
          localStorage.removeItem(key);
          return null;
        }
        //解密
        if (sysConfig.LS_ENCRYPTION == "AES") {
          value.content = JSON.parse(
            tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key)
          );
        }
        return value.content;
      }
      return null;
    } catch (err) {
      return null;
    }
  },
  remove(key) {
    return localStorage.removeItem(key);
  },
  clear() {
    return localStorage.clear();
  },
};

/*sessionStorage*/
tool.session = {
  set(table, settings) {
    var _set = JSON.stringify(settings);
    return sessionStorage.setItem(table, _set);
  },
  get(table) {
    var data = sessionStorage.getItem(table);
    try {
      data = JSON.parse(data);
    } catch (err) {
      return null;
    }
    return data;
  },
  remove(table) {
    return sessionStorage.removeItem(table);
  },
  clear() {
    return sessionStorage.clear();
  },
};

/*cookie*/
tool.cookie = {
  set(name, value, config = {}) {
    var cfg = {
      expires: null,
      path: null,
      domain: null,
      secure: false,
      httpOnly: false,
      ...config,
    };
    var cookieStr = `${name}=${escape(value)}`;
    if (cfg.expires) {
      var exp = new Date();
      exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000);
      cookieStr += `;expires=${exp.toGMTString()}`;
    }
    if (cfg.path) {
      cookieStr += `;path=${cfg.path}`;
    }
    if (cfg.domain) {
      cookieStr += `;domain=${cfg.domain}`;
    }
    document.cookie = cookieStr;
  },
  get(name) {
    var arr = document.cookie.match(
      new RegExp("(^| )" + name + "=([^;]*)(;|$)")
    );
    if (arr != null) {
      return unescape(arr[2]);
    } else {
      return null;
    }
  },
  remove(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = `${name}=;expires=${exp.toGMTString()}`;
  },
};

/* Fullscreen */
tool.screen = function (element) {
  var isFull = !!(
    document.webkitIsFullScreen ||
    document.mozFullScreen ||
    document.msFullscreenElement ||
    document.fullscreenElement
  );
  if (isFull) {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  } else {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    }
  }
};

/* 复制对象 */
tool.objCopy = function (obj) {
  return JSON.parse(JSON.stringify(obj));
};

/* 日期格式化 */
tool.dateFormat = function (date, fmt = "yyyy-MM-dd hh:mm:ss") {
  date = new Date(date);
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

/* 千分符 */
tool.groupSeparator = function (num) {
  num = num + "";
  if (!num.includes(".")) {
    num += ".";
  }
  return num
    .replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
      return $1 + ",";
    })
    .replace(/\.$/, "");
};

/* 常用加解密 */
tool.crypto = {
  //MD5加密
  MD5(data) {
    return CryptoJS.MD5(data).toString();
  },
  //BASE64加解密
  BASE64: {
    encrypt(data) {
      return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data));
    },
    decrypt(cipher) {
      return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8);
    },
  },
  //AES加解密
  AES: {
    encrypt(data, secretKey = sysConfig.LS_ENCRYPTION_key, config = {}) {
      if (secretKey.length % 8 != 0) {
        console.warn("[SCUI error]: 秘钥长度需为8的倍数,否则解密将会失败。");
      }
      const result = CryptoJS.AES.encrypt(
        data,
        CryptoJS.enc.Utf8.parse(secretKey),
        {
          iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
          mode: CryptoJS.mode[config.mode || "ECB"],
          padding: CryptoJS.pad[config.padding || "Pkcs7"],
        }
      );
      return result.toString();
    },
    decrypt(cipher, secretKey = sysConfig.LS_ENCRYPTION_key, config = {}) {
      const result = CryptoJS.AES.decrypt(
        cipher,
        CryptoJS.enc.Utf8.parse(secretKey),
        {
          iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
          mode: CryptoJS.mode[config.mode || "ECB"],
          padding: CryptoJS.pad[config.padding || "Pkcs7"],
        }
      );
      return CryptoJS.enc.Utf8.stringify(result);
    },
  },
};

export default tool;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值