vue插件 (Plugins)

52 阅读1分钟

在vue项目开发过程中,我们都会用到已经写好的插件!插件的存在确实方便了很多项目的开发!

那我们如何自己写一个插件呢?

先看看官网介绍吧:

企业微信截图_16938124379095.png

总的来说,插件拥有install方法,创建好插件方法后,再通过app.use()调用;

接下来自定义一个简单的插件吧!

该插件实现的是,在页面的任意地方点击,都会生成一个小圆球,圆球缓缓上升移动,之后消失。(优化一下样式,就可以实现气球放飞的效果)

首先,在plugins文件夹下创建一个box文件夹,再在box文件夹下创建box.ts和box.css;

box.ts 文件代码如下:

import './box.css'

export default {
  install: (app: any, options: any) => {
    const body = document.body

    body.addEventListener('click', (e) => {
      // 获取 点击位置 x, y
      const { pageX: x, pageY: y } = e;

      // 创建box实例
      const box = new Box(x, y);

      // 生成span标签
      const spanDom = document.createElement('span');
      // 获取随机颜色
      const boxColor = getColor();
      // 创建box
      box.create(spanDom, boxColor);

      // 清除创建的box标签 和 生成box时用的定时器删除
      setTimeout(() => {
        clearInterval(this.timer)
        box.remove(spanDom)
      }, 2000);

    })

  }
}
// 获取随机颜色方法
function getColor() {
  const colors = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
  const colorLen = colors.length;
  let color = '#';

  for (let i = 0; i < 6; i++) {
    const randomInd = Math.floor((0 - colorLen) * Math.random() + colorLen);
    color += colors[randomInd]
  }

  return color;
}
// 构造函数Box
function Box(x, y) {
  this.x = x;
  this.y = y;
  this.timer = null;
}
// 利用原型,增加create 创建方法
Box.prototype.create = function (domSpan: any, color: any) {
  const body = document.body
  let offset = 20;
  domSpan.style.left = this.x + 'px';
  domSpan.style.top = this.y + 'px';
  domSpan.style.backgroundColor = color;
  domSpan.className = 'box';

  this.timer = setInterval(() => {
    domSpan.style.top = this.y - offset + 'px';
    offset++;
  })

  body.appendChild(domSpan);
}
// 利用原型,增加remove 删除方法
Box.prototype.remove = function (domSpan) {
  domSpan.remove();
}

box.css 代码如下:

.box {
  width: 20px;
  height: 20px;
  position: absolute;
  z-index: 999999;
}

之后在main.ts中通过app.use 调用插件

import App from './App.vue'
import box from '@/plugins/box/box'

const app = createApp(App)
app.use(box)

这样就能在全局创建一个点击动态生成小球的 插件了!

如有问题,及时沟通纠正!