Vue-实现div弹窗可自由拖拽(亲测有效)

欢迎来到小柠檬的博客

要实现一个弹窗的自由拖拽功能,只需要四步骤,即可轻松完成,以下代码可以直接复制粘贴,项目总结,亲测可用

第一步:

1: 在目录下新建一个文件夹,文件夹内新建js文件,命名为:drag.js。如图所示:
在这里插入图片描述

第二步:

2: 在drag.js中写上如下代码(使用的话直接复制即可):

import Vue from 'vue';
//使用Vue.directive()定义一个全局指令
//1.参数一:指令的名称,定义时指令前面不需要写v-
//2.参数二:是一个对象,该对象中有相关的操作函数
//3.在调用的时候必须写v-
const drag = Vue.directive('drag', {
    //1.指令绑定到元素上回立刻执行bind函数,只执行一次
    //2.每个函数中第一个参数永远是el,表示绑定指令的元素,el参数是原生js对象
    //3.通过el.focus()是无法获取焦点的,因为只有插入DOM后才生效
    bind: function (el) { },
    //inserted表示一个元素,插入到DOM中会执行inserted函数,只触发一次
    inserted: function (el) {
        el.onmousedown = function (e) {
            var disx = e.pageX - el.offsetLeft;
            var disy = e.pageY - el.offsetTop;
            document.onmousemove = function (e) {
                el.style.left = e.pageX - disx + 'px';
                el.style.top = e.pageY - disy + 'px';
            }
            document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
            }
        }
    },
    //当VNode更新的时候会执行updated,可以触发多次
    updated: function (el) { }
})
export default drag;

第三步:

3: 在main.js中引入该指令:

import drag from '@/config/drag';

第四步:

4: 在需要实现拖拽的div中,加入指令:v-drag

 <!-- 拖拽弹窗 -->
      <div class="goinvoice" v-if="invoiceflag">
        <div class="main" v-drag>
          <!-- 中间应收劳务 -->
          <div class="top">
            <div class="message guanbi">
              <div>
                货物或应税劳务、服务名称
                <span>
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-mc-ywjc"></use>
                  </svg>
                </span>
              </div>
              <i class="el-icon-close right" @click="invoiceflag = false"></i>
            </div>
            <!-- 劳务列表 -->
            <div class="foot-box">
              <div>
                <template>
                  <el-table
                    ref="multipleTable"
                    tooltip-effect="dark"
                    :data="tableData"
                    style="width: 100%"
                    height="197"
                  >
                    <el-table-column type="index" width="50" label="序号">
                    </el-table-column>
                    <el-table-column
                      prop="commodityName"
                      label="货物(劳务)名称"
                      min-width="150"
                      show-overflow-tooltip
                    >
                    </el-table-column>
                    <el-table-column prop="tax" label="税额" width="150">
                      <template slot-scope="scope">
                        <span>{{ fixed(scope.row.tax * 1) }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 拖拽弹窗 -->

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hong521520/article/details/106804209
今日推荐