Vue自定义指令

1,072 阅读2分钟

前景

vue中有很多内置的指令,如v-for , v-if , v-html , v-on等; 然而,有的情况下,我们仍然需要对普通DOM元素进行底层操作,这时候就会用到自定义指令。

自定义指令

接下来用一个时间转换自定义指令来讲解,该自定义的指令作用:将一个时间转换为离现在时间的距离,是刚刚,还是一分钟前,还是一小时前等。

代码

在vue实例中初始化当前时间

data:{
         timeNow:new Date().getTime(),
     },

提供时间格式化工具类

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分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) {
        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;
    },
    //转换时间
    getFormatTime: function (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;
    }
}

自定义指令的代码

Vue.directive('time', {
                bind: function (el, binding) {
                    //准备工作,例如,添加事件处理器或只需要运行一次高耗时工作
                    el.innerHTML = Time.getFormatTime(binding.value);
                    el.timeOut = setInterval(function(){
                        el.innerHTML = Time.getFormatTime(binding.value);
                    },1000);
                },
                update: function (newValue, oldValue) {
                    //值更新时的工作,也会以初始值为参数调用一次
                    console.log('newValue:' + newValue, 'oldValue:' + oldValue);
                },
                unbind: function (el) {
                    //清理工作,例如,删除bind()添加的事件监听器
                    clearInterval(el.timeOut);
                    delete el.timeOut;
                }
            });

模板中的引用

<div v-time="timeNow"></div>