vue3中通过自定义指令(实现拖拽drag功能)

vue3中使用自定义指令,实现拖拽drag功能

 


在utils文件夹下,新建directives.ts

// 拖拽的指令
const drag = {
  beforeMount(el: any, binding: any) {
    // 自定义属性,判断是否可拖拽
    if (!binding.value) return
    const dialogHeaderEl = el.querySelector('.dialog_header')
    const dragDom = el.querySelector('.dialog_content')
    dialogHeaderEl.style.cssText += ';cursor:move;'
    // dragDom.style.cssText += ';bottom:0px;'

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = (function () {
      if ((document.body as any).currentStyle) {
        // 在ie下兼容写法
        return (dom: any, attr: any) => dom.currentStyle[attr]
      }
      return (dom: any, attr: any) => getComputedStyle(dom, null)[attr]
    })()

    dialogHeaderEl.onmousedown = (e: any) => {
      // 鼠标按下,计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft
      const disY = e.clientY - dialogHeaderEl.offsetTop
      const screenWidth = document.body.clientWidth // body当前宽度
      const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度,可某些环境下无法获取)

      const dragDomWidth = dragDom.offsetWidth // 对话框宽度
      const dragDomheight = dragDom.offsetHeight // 对话框高度

      const minDragDomLeft = dragDom.offsetLeft
      const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

      const minDragDomTop = dragDom.offsetTop
      const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight

      // 获取到的值带px 正则匹配替换
      let styL = sty(dragDom, 'left')
      // 为兼容ie
      if (styL === 'auto') styL = '0px'
      let styT = sty(dragDom, 'top')

      // console.log(styL)
      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (styL.includes('%')) {
        styL = +document.body.clientWidth * (+styL.replace(/%/g, '') / 100)
        styT = +document.body.clientHeight * (+styT.replace(/%/g, '') / 100)
      } else {
        styL = +styL.replace(/px/g, '')
        styT = +styT.replace(/px/g, '')
      }

      document.onmousemove = function (e) {
        // 通过事件委托,计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY
        // 边界处理
        if (-(left) > minDragDomLeft) {
          left = -(minDragDomLeft)
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft
        }

        if (-(top) > minDragDomTop) {
          top = -(minDragDomTop)
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop
        }

        // 移动当前元素
        dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
      }

      document.onmouseup = function (e: any) {
        document.onmousemove = null
        document.onmouseup = null
      }
      return false
    }
  }
}
// 挂载,注册
const directives = {
  install: function (app: any) {
    app.directive('dialogDrag', drag)
  }
};
export default directives;

自定义全局指令:app的 directive 方法,可以在任意组件中被使用;

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import Directives from "@/utils/directives"
// ...
const app = createApp(App)
// 自定义全局指令,可以在main.js 的app上注册就可以全局使用
app.use(Directives)

在页面组件中使用方式:v-dialogDrag

<template>
 <div class="dialog_wrap" v-dialogDrag="true" >
 // 整个区域
  <div class="dialog_content" >
      // 可按下拖动的位置
    <div class="dialog_header">
         //...
    </div>
    // 其他
  </div>
 </div>
</template>
<style lang="scss" scoped>
.dialog_content{
    position: fixed;
    right: 0;
    bottom: 0;
    width: 392Px;
    height: 580Px;
    .dialog_header{
       height: 50Px;
       width: 100%;
     }
}
</style>

拓展学习:vue2.x和vue3.x的自定义指令区别?

  • 在vue3.0中指令的注册和其生命周期是这样的:

import { createApp } from 'vue'
const app = createApp({})

// 注册
app.directive('my-directive', {
  // Directive has a set of lifecycle hooks:
  // 在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的 v-on 事件监听器调用前的事件监听器中时,这很有用。
  created(){},
  // 当指令第一次绑定到元素并且在挂载父组件之前调用
  beforeMount() {},
  // 在绑定元素的父组件被挂载前调用
  mounted() {},
  // 在更新包含组件的 VNode 之前调用
  beforeUpdate() {},
  // 在包含组件的 VNode 及其子组件的 VNode 更新后调用
  updated() {},
  // 在卸载绑定元素的父组件之前调用
  beforeUnmount() {},
  // 当指令与元素解除绑定且父组件已卸载时,只调用一次
  unmounted() {}
})
// 自定义指令 API 钩子函数的参数 (有 el、binding、vnode 和 prevVnode)
  • 在vue2.x中指令的注册和其生命周期是这样的:

  • import Vue from 'vue'
    // 注册
    Vue.directive('my-directive', {
      bind: function () {},
      inserted: function () {},
      update: function () {},
      componentUpdated: function () {},
      unbind: function () {}
    })
    

    全局directive

  • 与Vue 2.x的使用方法基本相同
  • 在main.js中添加全局directive,可以在任意组件中被使用
  • 在3.0中创建vue实例的方式不再是new Vue,而是使用createApp方法进行创建
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.directive('focus', {
    // When the bound element is mounted into the DOM...
    mounted(el) {
        // Focus the element
        console.log(el);
        el.focus()
    }
})
app.mount('#app')
  • 在其他单文件组件调用全局directive
<template>
    <input type="text" name="" id="" v-focus>
</template>

局部使用directive

  • 与Vue 2.x的使用方法基本相同
  • 组件中通过 directives 选项,只能在当前组件中使用;
<template>
	<input type="text" name="" id="" v-focus>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() { return { };},
  directives: {
    focus: {
    	// 参数 el, binding, vnode, oldVnode
    	mounted: function (el) { 
	       el.focus()
	    }
    }
 }
}
</script>

  • 19
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

回忆哆啦没有A梦

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值