Vue 自定义指令有全局注册和局部注册两种方式,这里使用注册全局指令的方式,通过 Vue.directive( id, [definition] ) 方式注册全局指令。然后在入口文件中进行 Vue.use() 调用。
1、在src目录下创建 directives文件夹,创建两个index.js,instruction.js
index.js
import { moretable, loadmore} from './instruction' //指令加多少就写在这个文件里,在花括号和下面的申明下
// 自定义指令
const directives = {
moretable
};
// 批量注册指令
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
}
instruction.js
import Vue from 'vue'
// 注册 表格滚动底部指令
const moretable = Vue.directive('moretable', {
bind(el, binding) {
// 获取element-ui定义好的scroll盒子 表格滚动底部事件
const TABLE_DOM = el.querySelector('.el-table__body-wrapper')
TABLE_DOM.addEventListener('scroll', function () {
const CONDITIONVALUE = this.scrollHeight - this.scrollTop <= this.clientHeight
if (CONDITIONVALUE) {
binding.value()
}
})
}
})
export { moretable }
2、main.js 中加入
import Directive from './directives/index.js'
Vue.use(Directive)
3、在组件中使用:
methods: {
moretable() {
if (this.total > this.tableData.length) {
//加载下一页数据
}
}
}