vue自定义指令的使用

128 阅读1分钟

使用场景

例如:选择器需要前端做分页的时候

需要触底时进行数据请求

1.在元素中自定义指令 v-select-more="loadMore"

2.定义自定义指令内容

directives: {
        'select-more': {
        //bind会在初始化时执行一次,该例中是为元素绑定scroll事件
            bind(el, binding, vm) {
                // 获取scroll盒子
                const SELECTWRAP_DOM = el.querySelector('元素类名');
                el.addEventListener('scroll', function() {
                    const condition = this.scrollHeight - this.scrollTop <= this.clientHeight;
                    // 判断滚动到底部  (condition:如果元素滚动到底, 下面等式返回true, 没有则返回false)
                    if (condition) {
                        // binding.value 为自定义指令绑定的值
                        binding.value();
                    }
                });
            }
        },
    },

在methods中定义loadMore的具体实现,向后台请求数据

3.在项目中如果有多个下拉触底分页 可以考虑将下拉框封装成组件 or 将自定义指令抽成全局自定义,全局自定义如下

总之,对于重复性代码要思考进行提取与归并

  • 全局定义
//  utils/directive
export const selectMore = {
        bind: function(el, binding) {
            const callback = binding.value;
            el.addEventListener('scroll', (e) => {
                binding.def.scroll(e, callback);
            });
        },
        scroll: function(e, callback) {
            const targetDom = e.target;
            const innerDom = targetDom.children[0];
            if ((targetDom.scrollTop + targetDom.clientHeight >= innerDom.clientHeight)) {
                callback && callback();
            }
        },
        unbind: function(el, binding) {
            const callback = binding.value;
            el.removeEventListener('scroll', (e) => binding.def.scroll(e, callback));
        }
}
// utils/directives
const directives = {
   selectMore,
};

const globalDirectives = {
    install: function(Vue, option) {
        Object.keys(directives).forEach((key) => {
            Vue.directive(key, directives[key]);
        });
    }
};

export default globalDirectives;
  • 全局引入
// index.js
import globalDirectives from '../../utils/directives';
Vue.use(globalDirectives);
  • 使用:同上 v-select-more="loadMore"

参考资料:

blog.csdn.net/edwardwzw/a… blog.csdn.net/jarisMA/art…