1.10 Vue 自定义指令

为什么使用自定义指令

  • 在vue2中,代码复用和抽象的主要形式是组件。然而,有的情况下,我们仍然需要对普通DOM元素进行底层操作,这时候就会用到自定义指令
  • 除了内置指令(v-for/v-if/v-else/v-else-if/v-model/v-bind/v-on/v-show/v-text…), Vue. js也允许注册自定义指令。
  • 自定义指令提供一种机制将数据的变化映射为DOM行为。
  • 可以用vue.directive(id, definition)方法注册一个全局自定义指令,它接收两个参数指令ID与定义对象。也可以用组件的 directives选项注册一个局部自定义指令。
一个指令定义对象可以提供如下几个钩子函数 (均为可选):
  • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
  • inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新。
  • componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
  • unbind:只调用一次,指令与元素解绑时调用。
<script>
// 定义
Vue.directive('my-directive', {
    bind: function () {
        // 准备工作
        // 例如,添加事件处理器或只需要运行一次的功耗任务
    },
    update: function(newValue, oldValue){
        // 值更新时的工作
        // 也会以初始值为参数调用一次
    },
    unbind: function() {
        // 清理工作
        // 例如,删除bind()添加的事件监听器
    }
})
</script>
<!-- 使用 -->
<div v-my-directive="someValue"></div>
指令钩子函数会被传入以下参数:
  • el:指令所绑定的元素,可以用来直接操作 DOM 。
  • binding:一个对象,包含以下属性:
    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-my-directive=“1 + 1” 中,绑定值为 2。
    • oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
    • expression:字符串形式的指令表达式。例如 v-my-directive=“1 + 1” 中,表达式为 “1 + 1”。
    • arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 “foo”。
    • modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
  • vnode:Vue 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
动态指令参数

指令的参数可以是动态的。例如,在 v-mydirective:[argument]=“value” 中,argument 参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。

函数简写

在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写:

Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})
对象字面量

如果指令需要多个值,可以传入一个 JavaScript 对象字面量。记住,指令函数能够接受所有合法的 JavaScript 表达式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>
<script>
Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
})
</script>

熟悉自定义指令

编写时间显示插件demo

效果图
在这里插入图片描述
文件结构
|- js
|  |- time.js
|- index.html

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
    <script src="./js/time.js"></script>
</head>
<body>
    <div id="app">
        <div v-time="timeNow1"></div>
        <div v-time="timeNow2"></div>
        <div v-time="timeNow3"></div>
    </div>
    <script>
    var app = new Vue({
        el: "#app",
        data: {
            timeNow1: new Date().getTime() - 10 * 1000,// 10秒
            timeNow2: new Date().getTime() - 60 * 1000,// 1分钟
            timeNow3: new Date().getTime() - 60 * 1000 * 60// 1小时
        }
    })
    </script>
</body>
</html>

js/time.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分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(); // 今天0点的时间戳
        var year = this.getYearUnix(); // 今年0点的时间戳
        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 * 10)// 十秒检测一次
    },
    unbind: function(el) {
        clearInterval(el.timeOut)
        delete el.timeOut
    }
})
发布了56 篇原创文章 · 获赞 20 · 访问量 7360

猜你喜欢

转载自blog.csdn.net/qq_36826618/article/details/104243839