zoukankan      html  css  js  c++  java
  • 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)
        })
        
  • 相关阅读:
    PHP 函数
    PHP 循环
    PHP 数组
    PHP Switch 语句
    PHP If...Else 语句
    PHP 字符串
    PHP 变量
    用where导致group by分组字段的索引失效
    mysql之filesort原理
    Windows定时开机并开启工作软件
  • 原文地址:https://www.cnblogs.com/guojiabing/p/11352666.html
Copyright © 2011-2022 走看看