美文网首页
vue 编写拖拽可缩放改变宽度的插件

vue 编写拖拽可缩放改变宽度的插件

作者: 简单tao的简单 | 来源:发表于2024-03-06 14:04 被阅读0次
image.png
image.png
  1. 编写 drag.js 放在 utils 文件夹里

/**
*拖拽改变宽度的指令
*/
export default {
    install(Vue) {
        Vue.mixin({
            directives: {
                drag: {
                    inserted: function (el) {
                        const dragDom = el;
                        dragDom.style.cursor = "e-resize";
                        dragDom.style.userSelect = "none";
                        dragDom.onmousedown = e => {
                            //设置捕获范围
                            if (dragDom.setCapture) {
                                dragDom.setCapture();
                            } else {
                                window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                            }
                            //鼠标按下,计算当前元素距离可视区的距离
                            const disX = e.clientX;
                            const w = dragDom.clientWidth;
                            const minW = 240;
                            const maxW = 6000;
                            console.log('disX, w', disX, w)
                            var nw;
                            window.onmousemove = function (e) {
                                //通过事件委托,计算移动的距离
                                const l = e.clientX - disX;
                                nw = w - l;
                                if (nw < minW) {
                                    return false;
                                }
                                dragDom.style.width = `${nw}px`;
                            }
                            window.onmouseup = function (e) {
                                window.onmousemove = null;
                                window.onmouseup = null;
                                if (dragDom.releaseCapture) {
                                    dragDom.releaseCapture();
                                } else {
                                    window.releaseEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                                }
                            }
                        }
                    }
                }
            }
        })
    }
}
  1. 在main.js 里引入
import drag from './utils/drag.js'
Vue.use(drag);
  1. 在组件里使用
<div class="fold-box-warp" ref="foldBoxWarp" v-drag ></div>

知识点总结

  1. 使用插件Vue.use(MyPlugin)
  2. 开发插件 :Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象.
  3. Vue.mixin 逻辑复用
  4. directives 自定义指令

相关文章

网友评论

      本文标题:vue 编写拖拽可缩放改变宽度的插件

      本文链接:https://www.haomeiwen.com/subject/josjzdtx.html