什么是自定义指令?
为了让vue识别到我们使用以v-开头的行内属性,就是常用的指令。然而,,在 Vue2.0 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。
自定义指令又包含了全局自定义和局部自定义指令。
<template>
<div>
//设置自动获取焦点指令
<input v-focus/>
</div>
</template>
全局自定义指令方法:
// 注册一个全局自定义指令 `v-focus`
// (注册的名称、描述)
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
组件内使用的自定义指令方法:
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
通常用到的钩子函数有以下这些*:
bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 。
componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
unbind:只调用一次,指令与元素解绑时调用。
钩子函数参数:
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 钩子中可用
手写图片懒加载自定义指令:
代码如下:
<template>
<div>
<p v-for="(item,index) in imgs" :key="index">
<img v-lazyLoad="item" alt="">
</p>
</div>
</template>
<script>
import Vue from "vue"
Vue.directive("lazyLoad",{
bind: function (el,binding){
let lazyLoadObser = new IntersectionObserver((entries,observer)=>{
console.log(entries.target);//img
entries.forEach((item,index)=>{
let lazyImg = item.target
if(item.intersectionRatio > 0){
lazyImg.src = binding.value
lazyLoadObser.unobserve(lazyImg)
}
})
})
lazyLoadObser.observe(el)
}
})
export default {
data(){
return{
imgs:[
'https://img0.baidu.com/it/u=259849153,4031030453&fm=26&fmt=auto&gp=0.jpg',
'https://img0.baidu.com/it/u=2651628541,3421601007&fm=26&fmt=auto&gp=0.jpg',
'https://img0.baidu.com/it/u=1190999743,862853537&fm=26&fmt=auto&gp=0.jpg',
'https://img0.baidu.com/it/u=831219566,2605776766&fm=26&fmt=auto&gp=0.jpg',
'https://img2.baidu.com/it/u=114405908,2600222787&fm=26&fmt=auto&gp=0.jpg',
'https://img0.baidu.com/it/u=3996786119,3124154252&fm=26&fmt=auto&gp=0.jpg',
'https://img2.baidu.com/it/u=1896429556,2979512276&fm=26&fmt=auto&gp=0.jpg',
]
}
}
}
</script>