• vue定义全局date过滤器(自定义JS文件模块和Moment.js库)


    自定义dateFormat.js文件模块

    • dateFormat.js

        /**
         * 时间字符串 转 时间戳
         * @param {String} time_str 时间字符串(格式"2014-07-10 10:21:12")
         * @returns {Number} 10位数的时间戳(秒值:1404958872000)
         */
      const toTimestamp = time_str => +new Date(time_str) / 1000
      
      /**
       * 时间戳 转 时间字符串
       * @param {Number} time_stamp 10位数的时间戳(秒值:1404958872)
       * @returns {String} 时间字符串 (格式"2014-07-10 10:21:12")
       */
      const toTimestr = time_stamp => {
          const time = new Date(time_stamp * 1000);
          const Y = time.getFullYear()
          const M = (time.getMonth() + 1).toString().padStart(2, '0')
          const D = time.getDate().toString().padStart(2, '0')
          const h = time.getHours().toString().padStart(2, '0')
          const m = time.getMinutes().toString().padStart(2, '0')
          const s = time.getSeconds().toString().padStart(2, '0')
          return `${Y}/${M}/${D} ${h}:${m}:${s}`
      }
      
      export { toTimestamp, toTimestr}
      
    • vue项目的main.js文件中全局注册

      // 定义全局过滤器
      import * as filters from "./dateFormat";
      Object.keys(filters).forEach(key => {
          Vue.filter(key, filters[key])
      })
      

    JavaScript 日期处理类库Moment.js

    • vue项目的main.js文件中全局注册的两种形式

      • 第一种

            // 引入JavaScript 日期处理类库(格式化)
            import moment from "moment";
            // moment.locale('zh-cn') // 汉化
            
            /**
             * 全局挂载(适用于script标签中的js代码格式化时间)
             * 使用方式:this.$moment(时间).format('时间格式')
             */
            Vue.prototype.$moment = moment;
        
      • 第二种

        /**
         * 注册为全局过滤器(适用于template标签中的html代码 => 插值表达式和v-bind属性绑定)
         * 使用方式:<span>{{ 时间 | formatDate('时间格式') }}</span>
         * @parms { String } formatStr  时间格式:"Y-M-D h:m:s"
         * @parms { any } data 时间:可以是时间戳,也可以是其他形式的时间,比如2019/8/14
         * 时间戳要求是毫秒值,如果是秒值,需要在过滤前 * 1000变为毫秒值
         *  <span> {{ 1111111111 * 1000 | formatDate('Y-M-D h:m:s') }} </span> 
         * 'hh:mm:ss'是十二小时制时间,'HH:mm:ss'是二十四小时制时间
         */
        Vue.filter('formatDate', function (date: any, formatStr: string) {
            return moment(date).format(formatStr)
        })
        
  • 相关阅读:
    linux创建用户
    使用Myeclipse插件将wsdl生成java客户端代码
    JAVA时间格式转换大全
    数据库DDL语句书写规范
    jacon
    应用jacob组件造成的内存溢出解决方案(java.lang.OutOfMemoryError: Java heap space)
    为什么使用内部类
    HBase查找一条数据的过程
    Hadoop:输入,输出,key,value格式
    ArrayList和Vector的区别
  • 原文地址:https://www.cnblogs.com/guojiabing/p/11352666.html
Copyright © 2020-2023  润新知