vue 封装一个通过js调用的全局vue组件

1,473 阅读3分钟

前言

在使用vue项目编写的时候,不可避免的会碰到需要时js api来调用组件进行显示的情况

例如饿了么element ui 的 Notification 通知、Message 消息提示等组件

虽然已经提供了,但是由于api的限制,我们只能通过特定的参数来有限的改变组件的样式

之前的文章说过可以使用 new Vue()Vue.extends等方法来进行改变这些api组件的样式

但是同时它们也有个缺点,无法自动实时更新数据,也就是没有双向绑定,只能静态布局,为了解决这个痛点

我们自己动手封装一个全局js api调用组件,然后再把需要的数据传过去进去更新,自己动手丰衣足食

就以饿了么element-ui的通知组件Notification为例,实现一个全局通知弹窗下载进度条组件

正文

使用Vue.extend构造器来创建是最为方便的,不过和之前不同的是,这样创建的实例组件只能创建单个,每一次调用都会重新创建一个新的实例,不会对原有的实例进行更新,所以我,我们要对实例进行缓存,以便后续的数据更新

这里我以自定义创建一个下载进度弹窗通知为例

首先我们创建一个组件文件夹下的js文件

/components/DownLoadNotification/index.js

实现思路是用Vue.extend构造组件后,把api接收的参数直接传入组件data使用,并为每个实例生成id,拿出dom插入到全局body中,当生成多个实例时动态计算定位的偏移量避免组件重叠

import Vue from 'vue'
import component from './index.vue'

const DownLoadNotification = Vue.extend(component)

const instances = [] // 实例缓存列表

export const notify = (options) => {
  let instance; // 单个实例

  options.onClose = function() { // 把删除当前实例的方法传入组件内
    removeNotify(instance.id)
  }
  options.onCloseAll = () => { // 把删除所有实例的方法传入组件内
    removeNotifyAll()
  }

  // 直接控制实例的data,而不是通过propsData传入
  instance = new DownLoadNotification({
    data: options,
  })
  instance.id = Date.now(); // 生成id
  instance.$mount(); // 挂载,生成dom节点
  document.body.appendChild(instance.$el) // 把dom节点添加到body全局
  instance.visible = true // 先挂载节点再显示节点里的内容,可以出现过渡动画,而不是一开始全部显示

  // 计算多个实例时的偏移量
  // 第一个不需要计算,把push放到循环下面,数组为空时不会循环,第二次开始则会进行计算
  let verticalOffset = 0
  instances.forEach((item) => {
    verticalOffset += item.$el.offsetHeight + 16 // 每个组件高度间隔16px
  })

  verticalOffset += 16 // 首次最下面的组件底部距离最底部也有16px的间隙

  instance.verticalOffset = verticalOffset // 计算出来的偏移量赋值到组件中data

  instances.push(instance) // 缓存实例
  return instance
}

// 删除单个组件实例
function removeNotify(id) {
  const index = instances.findIndex(item => item.id === id)
  index !== -1 && instances.splice(index, 1)
}

// 删除所有组件实例
function removeNotifyAll() {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].close(); // 调用组件内的删除方法来同时删除实例和dom
  }
}

删除时既要清空组件dom又要删除实例,所以把在js中定义的删除实例方法传入组件,组件需要删除时调用即可

需要注意的是,当有多个全局组件,删除其中一个时,位置应当发生改变

所以删除其中的一个组件实例时要重新计算偏移量位置

重新改造一下 删除单个组件实例 的方法,大致做法就是,拿到被删除的当前实例的高度,然后从被删除实例的位置开始遍历,后面的实例逐一删除被删除的实例高度和边距

// 删除单个组件实例
function removeNotify(id) {
  let index = -1;
  const len = instances.length; // 未删除前数组总长度
  const instance = instances.filter((instance, i) => { // 获取保存当前删除的实例
    if (instance.id === id) {
      index = i; // 保存索引
      return true;
    }
    return false;
  })[0];
  instances.splice(index, 1); // 删除实例

  if (len <= 1) return // 只有一个实例时不需要重新计算位置
  const position = instance.position; // 获取实例定位字段
  const removedHeight = instance.$el.offsetHeight; // 获取实例高度

  for (let i = index; i < len - 1 ; i++) { // 从被删除的位置开始遍历
    if (instances[i].position === position) { // 修改的位置定位是否一致
      // 将后续元素的定位位置 减去 上一个删除的元素宽度 + 16px 的首次底部边距
      instances[i].$el.style[instance.verticalProperty] =
        parseInt(instances[i].$el.style[instance.verticalProperty], 10) - removedHeight - 16 + 'px';
    }
  }
}

接下来在编写组件/components/DownLoadNotification/index.vue

<template>
  <el-collapse-transition>
    <div v-if="visible" :class="['DownLoadNotification']" :style="positionStyle">
      <div class="header">
        <span>{{ fileName }}</span>
        <span>{{ fileSize }}</span>
      </div>
      <el-progress
        :percentage="downLoadProgress"
        :status="downStatus"
        :stroke-width="15"
      ></el-progress>
      <el-button @click="close" size="mini">关 闭</el-button>
    </div>
  </el-collapse-transition>
</template>
<script>
export default {
  data() {
    return {
      /* 自定义数据 */
      fileName: "",
      fileSize: "",
      downLoadProgress: 0,
      downStatus: "",

      /* 组件基础数据 */
      id: null, // 实例id
      visible: false, // 显示控制按钮
      position: "bottom-left", // 显示方位
      verticalOffset: 0, // 位置偏移量
      onClose: null, // js中传入的删除当前组件方法
      onCloseAll: null, // js中传入的删除所有组件方法
    };
  },
  computed: {
    // 默认纵向布局,定位为 左 或者 右 时边距为10px
    horizontalClass() {
      // 实例左偏移还是右偏移
      return this.position.indexOf("right") > -1 ? "right" : "left";
    },
    verticalProperty() {
      // 实例上还是下
      return /^top-/.test(this.position) ? "top" : "bottom";
    },
    positionStyle() {
      // 多个实例时的偏移量
      return {
        [this.verticalProperty]: `${this.verticalOffset}px`,
      };
    },
  },
  methods: {
    // 销毁当前组件
    close() {
      this.visible = false;
      this.$el.addEventListener("transitionend", this.destroyElement); // 添加事件,在过渡效果结束后再销毁组件
      this.onClose(); // 调用外面js传入组件的方法
    },
    // 销毁所有组件
    closeAll() {
      this.onCloseAll();
    },
    // 销毁组件方法
    destroyElement() {
      this.$el.removeEventListener("transitionend", this.destroyElement);
      this.$destroy(true);
    },
  },
};
</script>
<style lang="less" scoped>
.DownLoadNotification {
  width: 300px;
  height: 60px;
  background-color: #dcdfe6;
  position: fixed;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  padding: 20px;
  .header {
    color: #606266;
    margin-bottom: 10px;
  }
}
.right {
  right: 10px;
}
.left {
  left: 10px;
}
</style>

data中的自定数据的就相当于使用api传入的参数,当我们保存实例后,可以修改这个实例内的data,来达成实时更新的效果

多个实例使用案例参考

<template>
  <div id="app">
    <div class="btn">
      <el-button @click="show(1)">显示实例1</el-button>
      <el-button @click="addBtn(1)">增加进度</el-button>
    </div>
    <div class="btn">
      <el-button @click="show(2)">显示实例1</el-button>
      <el-button @click="addBtn(2)">增加进度</el-button>
    </div>
    <div class="btn">
      <el-button @click="show(3)">显示实例1</el-button>
      <el-button @click="addBtn(3)">增加进度</el-button>
    </div>
  </div>
</template>
<script>
import { notify } from "./components/DownLoadNotification/index.js";
export default {
  name: "App",
  data() {
    return {
      instance1: null,
      instance2: null,
      instance3: null,
    };
  },
  methods: {
    show(index) {
      this[`instance${index}`] = notify({
        fileName: `测试文件${index}.zip`,
        fileSize: "100mb",
        downLoadProgress: 0,
        downStatus: "success",
      })
    },
    addBtn(index) {
      this[`instance${index}`].downLoadProgress += 10
    },
  },
}
</script>
<style lang="less">
#app{
  display: flex;
  align-items: center;
}
.btn{
  display: flex;
  flex-direction: column;
}
</style>

GIF.gif

例子仅供参考,重要的是实现思路,或者可以去饿了么element-ui查看封装的通知组件的源码,实现思路大同小异!