el-dialog添加全局拖动v-drag指令

路径:src/utils/directives.js

export default (Vue)=>{
  Vue.directive("drag", {
    inserted: function (el) {
      let odiv = el;   //获取当前元素
      let flag = false;
      const elDialog = odiv.getElementsByClassName('el-dialog')[0]
      elDialog.getElementsByClassName('el-dialog__header')[0].style.cursor = 'move'
      odiv.onmousedown = (e) => {
        if(e.target.className !== 'el-dialog__header'){
          return
        }
        e.preventDefault();
        flag = true
        //算出鼠标相对元素的位置
        let disX = e.clientX - elDialog.offsetLeft;
        let disY = e.clientY - elDialog.offsetTop;

        odiv.onmousemove = (e)=>{
          e.preventDefault();
          if(!flag){
            return false
          }
          //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;

          //移动当前元素
          elDialog.style.left = left + 'px';
          elDialog.style.top = top + 'px';
          elDialog.style.margin = "0px";
          elDialog.style.marginTop = "0px";

        };
        odiv.onmouseup = (e) => {
          e.preventDefault();
          if(!flag){
            return false
          }
          odiv.onmousemove = null;
          odiv.onmouseup = null;
        };
      };
    }
  })
}


路径:src/main.js

import directives from '@/utils/directives.js'
Vue.use(directives)
<!--告警详情 弹窗-->
    <el-dialog
      v-bind="detailDialogOption"
      top="10vh"
      :modal-append-to-body="detailDialogOption.modalAppendToBody"
      :append-to-body="detailDialogOption.appendToBody"
      :view.sync="detailDialogOption.view"
      :visible.sync="detailDialogOption.show" v-drag>
      <component
        v-if="detailDialogOption.show"
        :is="detailDialogOption.view"
        :data="detailDialogOption.data"
        :visible.sync="detailDialogOption.show"
        @close="detailDialogOption.show = false"></component>
    </el-dialog>

推荐阅读更多精彩内容