vue自定义指令的使用(通过折叠效果演示)

Vue 2021-08-18 1222

需求:所有的查询区域全部都可折叠

这个需求其实使用传统方式可以简单的实现,但是可能需要写很多的重复代码,即使使用mixin+全局控制折叠样式+动态创建折叠的元素,依然会产生较多的代码,那么有更简单的方式吗?对于元素的操作,你很容易就想到了自定义指令,没错自定义指令可以非常轻松的解决这个需求,并且调用十分简单。

先看效果:

代码如下:

Vue.directive('fieldsetShow', {
    bind (el, binding, vnode) {
        const node = document.createElement('span');
        node.setAttribute('class', 'hide-fieldset el-icon-arrow-down');
        el.appendChild(node);
        // 不能使用innerHTML方式插入图标,会导致查询框下的下拉框无法下拉
        // el.innerHTML += '<span class="hide-fieldset el-icon-arrow-down"></span>'; // 插入折叠图标
        const arrowDown = el.querySelector('.hide-fieldset'); // 获取元素
        const fieldBox = el.querySelector('.field-box'); // 获取元素
        arrowDown.addEventListener('click', (e) => { // 点击图标时触发 事件
            const className = e.target.className; // 获取class
            if (className.includes('arrow-down')) { // 动态切换图标
                arrowDown.setAttribute("class", "hide-fieldset el-icon-arrow-right");
                fieldBox.setAttribute('style', 'display:none');
                el.setAttribute('style', "min-height: 46px"); // 修改查询区域的高度,实现折叠效果
                vnode.context.height = loadGridHeight(); // 获取下方表格的高度,并动态设置组件中data下height字段的数据,height就是表格的高度
            } else {
                arrowDown.setAttribute("class", "hide-fieldset el-icon-arrow-down");
                fieldBox.setAttribute('style', 'display:block');
                el.setAttribute('style', "min-height: 80px");
                vnode.context.height = loadGridHeight();
            }
        })
    },
})

 

标签:Vue

文章评论

评论列表

已有0条评论