vue官方提供很多指令,如:v-model,v-show,v-if,v-if等,他们都以v-开头。当这些指令不能满足我们实际开发需求时,我们还可以自定义指令。自定义指令主要分为全局自定义指令和局部自定义指令。
vue中自定义指令分为全局自定义指令和局部自定义指令,可以按需使用。但大部分情况下使用的是全局自定义指令。自定义指令中有五个钩子函数,分别为:
1-bind 被绑定, 2-inserted 被插入, 3-update 开始更新, 4-componentUpdated 更新完成,5-unbind 解除绑定,其中比较常用的是bind和update
vue.use() 插件挂载,其内置有一个install属性
用法:安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。
该方法需要在调用 new Vue() 之前被调用。
当 install 方法被同一个插件多次调用,插件将只会被安装一次。
const refresh = {
bind(el, binding) {
let value = ''
el.addEventListener('input', function () {
console.log(el.querySelector('.el-select__input')?.value)
value = el.querySelector('.el-select__input')?.value
})
// 获取滚动页面DOM
const SCROLL_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
let scrollPosition = 0
//el.addEventListener可直接对当前dom元素进行滚动监听,实现当前dom元素的触底刷新功能
SCROLL_DOM.addEventListener('scroll', function () {
// 当前的滚动位置 减去 上一次的滚动位置
// 如果为true则代表向上滚动,false代表向下滚动
const flag = this.scrollTop - scrollPosition > 0
// 记录当前的滚动位置
scrollPosition = this.scrollTop
// 记录滚动位置距离底部的位置,在滚动位置距离滚动页面底部一定高度时在触发,例如距页面底部只有100px时触发loadMore事件
const LIMIT_HEIGHT = 10
const scrollBottom = this.scrollHeight - (this.scrollTop + this.clientHeight) < LIMIT_HEIGHT
const { loadMore } = binding.value
// 如果已达到指定位置则触发
// 如果向下滚动 并且距离底部只有10px
if (flag && scrollBottom) {
// 将滚动行为告诉组件
loadMore(true, value)
}
// 如果是向上滚动 并且距离顶部只有100px
// if (!flag&& this.scrollTop < LIMIT_HEIGHT) {
// loadMore(flagToDirection, value)
// }
})
}
}
export default refresh
index.js
import refresh from './loadMore'
const directives = {
refresh
}
export default {
install(Vue) {
Object.keys(directives).forEach(key => {
Vue.directive(key, directives[key])
})
}
}
main.js
import Directive from './directive/index';
Vue.use(Directive); // 自定义输入指令