继上篇 Vue 滚动触底 mixins,将对于文档滚动触底的逻辑迁移到某个dom上,将会用到 Vue.directive 来实现代码逻辑复用。vue
元素实现滚动的条件有两个:node
Element.scrollHeight这个只读属性是一个元素内容高度的度量,包括因为溢出致使的视图中不可见内容。bash
能够简单的理解为,滚动高度是元素能够滚动的最大值,分为两种状况app
滚动高度 = 当前元素的 clientHeight = height + padding
滚动高度 = 当前元素的padding + 子元素的clientHeight + 子元素的(padding,margin,border) + 伪元素(:after,:before)
Element.scrollTop 属性能够获取或设置一个元素的内容垂直滚动的像素数。dom
须要注意的是,scrollTop 是针对产生滚动条的元素而言,因此分为两种状况函数
为了简单起见,假设 father 和 child 都只设置了宽高。post
<div class="father" ref="father">
<div class="child" ref="child"></div>
</div>
// 若为真说明触底
father.clientHeight + father.scrollTop >= child.scrollHeight
复制代码
参数1
指令名称,如focus 使用的时候就经过 v-focus 去绑定指定dom测试
参数2
options配置项,包含如下的钩子函数,分别在对应的生命周期触发ui
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
bind(){
// 只调用一次,指令第一次绑定到元素时调用。在这里能够进行一次性的初始化设置。
},
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
},
update(){
// 所在组件的 VNode 更新时调用
},
componentUpdated(){
// 指令所在组件的 VNode 及其子 VNode 所有更新后调用。
},
unbind(){
// 只调用一次,指令与元素解绑时调用。
}
})
复制代码
上面的钩子函数都接受 el、binding、vnode 和 oldVnode
这些回调参数,对经常使用的参数作下解释spa
绑定的元素
,能够用来直接操做 DOM 。是绑定组件的data中的变量名
来讲下 value 和 arg 的区别,假设咱们想向指令传递特定的数据,能够经过下面的方式arg传递值,和 value绑定值只能使用一种
// 经过 binding.value 接收
<div v-test="title">这里是测试</div>
// 经过 binding.arg 接收
<div v-test:id1>测试2</div>
复制代码
// 在单独一个文件中单独管理全部 directive
import Vue from 'vue'
import inputClear from './input-clear'
import forNested from './picker-item-for-nested'
import copy from "./copy";
const directives = {
copy,
'input-clear':inputClear,
'for-nested':forNested
}
Object.keys(directives).forEach(key=>{
Vue.directive(key,directives[key])
})
复制代码
export default {
directives:{
// 自定义指令的名字
autoFocus:{
inserted(el){
el.focus()
console.log( 'inserted' );
}
}
}
}
复制代码
// directive.js
export default {
install(Vue){
Object.keys(directives).forEach(key=>{
Vue.directive(key,directives[key])
})
}
}
// main.js
import Directives from "./directive/index";
// Vue.use 经过注册插件的方式来注册指令 `Vue 插件中 install 函数接受 Vue构造函数做为第一入参`
Vue.use(Directives);
复制代码
// 接收一个 plugin 参数能够是 Function 也能够是 Object
Vue.use = function (plugin: Function | Object) {
// 若是传入的是对象,须要有一个install 方法,并执行该方法
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
// 若是传入的是是函数则当即执行
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
}
复制代码
若是子元素有多个,须要计算每一个子元素的 height + padding + border + margin
因此为了方便使用,滚动目标的子元素有多个的状况下,用一个标签统一包裹
function isBottom(el){
const child = el.children[0]
if(el.clientHeight + el.scrollTop >= child.scrollHeight){
console.log('触底了');
}
}
Vue.directive('scroll',{
bind(el){
el.addEventListener('scroll',function(){
isBottom(el)
})
},
unbind(el){
el.removeEventListener(isBottom)
}
})
复制代码
重点: