开发一个vue自定义指令的npm库-系列二:如何同时支持vue2、vue3实例的typescript类型

文章介绍了如何在Vue2和Vue3中兼容处理自定义指令的typescript类型,通过使用vue-demi库动态导入相应Vue版本的模块,根据项目版本调整类型定义。示例展示了svgWheel和svgDrag两个自定义指令的实现,它们分别用于SVG图像的缩放和拖拽操作。
摘要由CSDN通过智能技术生成

vue2、vue3中绑定自定义vue指令的用法是不一样的,vue2是绑定到Vue上,而vue3是绑定到createApp返回的vue实例上,所以typescript类型自然也不一样

import Vue from "vue";
import App from "./App.vue";

import { svgWheel, svgDrag } from "svg-zoom-drag-vue-directives";
svgWheel(Vue);
svgDrag(Vue);

new Vue({
  render: (h) => h(App),
}).$mount("#app");

Vue3

import { createApp } from "vue";
import App from "./App.vue";

import { svgWheel, svgDrag } from "svg-zoom-drag-vue-directives";
const app = createApp(App);
svgWheel(app);
svgDrag(app);

app.mount("#app");

那么,问题来了

如何同时支持vue2、vue3实例的typescript类型

经过调研,我使用vue-demi这个库,vue-demi会根据当前项目vue版本,从其定义的不同vue版本的模块导入模块,从而ts类型也会指向不同定义

import { Vue2, App } from "vue-demi";

如果当前项目是vue2,Vue2指向的是本地项目中vue的Vue2类型,则typeof Vue2就能取到正确类型,App会指向vue-demi定义的vue3版本中的App类型,使用重载写法来缩小范围,根据传参,最终类型会是typeof Vue2

如果当前项目是vue3,Vue2类型会指向vue-demi定义的vue3版本中的any类型,App会指向本地项目中vue的App类型,使用重载写法来缩小范围,根据传参,最终类型会是App<Element>

这样就可以实现同时支持vue2、vue3实例的typescript类型,有更好的写法也可以分享一下

import { Vue2, App } from "vue-demi";

/** create a `v-svgWheel` directive for a Vue app, allows the user to control the zoom in and out of an SVG image using the mouse wheel. */
export function svgWheel(app: typeof Vue2): void;
/** create a `v-svgWheel` directive for a Vue app, allows the user to control the zoom in and out of an SVG image using the mouse wheel. */
export function svgWheel(app: App<Element>): void;
// Control the zoom in and out of an SVG image by setting the viewbox attribute of the SVG element. The third parameter of the viewbox controls the horizontal size, while the fourth parameter sets the vertical size.
export function svgWheel(app: typeof Vue2 | App<Element>) {
  app.directive("svgWheel", (el: HTMLElement) => {
    if (el) {
      el.onwheel = (e: WheelEvent) => {
        // Because the SVG is rendered using v-html, the child element of the bound DOM is the SVG element.
        const svgDom = el.firstChild as SVGSVGElement;
        const viewBox = svgDom.getAttribute("viewBox") as string;
        const [x, y, width, height] = viewBox.split(/\s+/).map(parseFloat);
        // event.wheelDelta has been deprecated, use event.deltaY instead.
        // event.deltaY returns a positive value when scrolling downwards and a negative value when scrolling upwards. Otherwise, it is 0. event.wheelDelta is the opposite.
        const scaleDelta = e.deltaY > 0 ? 0.9 : 1.1; // Zoom scale.
        const newWidth = width * scaleDelta;
        const newHeight = height * scaleDelta;
        // Calculate the centering offset.
        const dx = (width - newWidth) / 2;
        const dy = (height - newHeight) / 2;
        const newViewBox = `${x + dx} ${y + dy} ${newWidth} ${newHeight}`;
        svgDom.setAttribute("viewBox", newViewBox);
      };
    }
  });
}

/** create a `v-svgDrag` directive for a Vue app, allows the user to drag the SVG image by holding down the mouse and moving the cursor. */
export function svgDrag(app: typeof Vue2): void;
/** create a `v-svgDrag` directive for a Vue app, allows the user to drag the SVG image by holding down the mouse and moving the cursor. */
export function svgDrag(app: App<Element>): void;
// Control the drag of an SVG image by setting the "viewBox" attribute of the SVG element. The first parameter of "viewBox" controls the left-right position, and the second parameter sets the up-down position.
export function svgDrag(app: typeof Vue2 | App<Element>) {
  app.directive("svgDrag", (el: HTMLElement) => {
    let clientX = 0; // The last x-axis position of the mouse
    let clientY = 0; // The last y-axis position of the mouse
    let debounce = true; // Throttling is necessary, otherwise the dragging effect will appear jerky
    let isStartMoveSvg = false; // Whether to start dragging
    let ratio = 1; // The ratio of drag speed to size
    let sgvDom: SVGAElement; // The SVG element
    let viewBox: string; // The "viewBox" attribute of the SVG element
    let arrPoint: number[]; // The value of the "viewBox" attribute of the SVG element
    // Mouse down means start moving
    el.onmousedown = () => {
      isStartMoveSvg = true;
      const width = el.getBoundingClientRect().width;
      // Because the SVG is rendered using "v-html", the child element of the bound command DOM is the SVG element
      sgvDom = el.firstChild as SVGAElement;
      viewBox = sgvDom.getAttribute("viewBox") as string;
      arrPoint = viewBox.split(/\s+/).map(parseFloat);
      // Dynamically adjust the drag speed based on the size, otherwise it becomes harder to drag as the SVG becomes smaller
      ratio = arrPoint[2] / width;
      if (ratio < 1) ratio = 1;
    };
    // Mouse up means end moving
    el.onmouseup = () => {
      isStartMoveSvg = false;
      clientX = 0;
      clientY = 0;
    };
    // Dynamically set "viewBox" while moving
    el.onmousemove = (e: MouseEvent) => {
      if (debounce) {
        debounce = false;
        if (isStartMoveSvg) {
          if (clientX !== 0 && clientY !== 0) {
            arrPoint[0] = arrPoint[0] - (e.clientX - clientX) * ratio;
            arrPoint[1] = arrPoint[1] - (e.clientY - clientY) * ratio;
            sgvDom.setAttribute("viewBox", arrPoint.join(" "));
          }
          clientX = e.clientX;
          clientY = e.clientY;
        }
        setTimeout(() => {
          debounce = true;
        }, 50);
      }
    };
  });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值