vue封装通用的通知组件alert__Vue.js
发布于 3 年前 作者 banyungong 1223 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

继上次搭完一个组件库的基本框架, 今天再来实现一个通用组件(alert)的开发, 使用方式与普通组件不一样,它是函数式调用(例如: this.$alert('test')), 与之类似的组件还有loding、message这些通用的函数式组件. 实现方法也与之类似, 这里就来实现alert组件

需要用到一些vue的api

const Alert = Vue.extend(alert) // 使用基础 Vue 构造器,创建一个“子类”

const Instance = new Alert({}) // 实例化组件

let vm = Instance.$mount() // 挂载, vm 就是组件里的this

效果图

养成良好习惯, 吹牛要先上效果图, 大家满意了的话,不妨点个👍再往下看.

为了美观,图中的button组件是模仿elementui的button样式的

代码

packages/alert/src/alert.vue

先附上代码, 组件中的样式和动画部分就省略了,button比较简单也省略了, 你可以根据业务需求去定制

<template>
  <transition name="fade">
    <div class="biu-alert-wrapper" v-show="show">
      <transition name="show">
        <div class="biu-alert-main" v-show="show">
          <div class="biu-header-cont">
            <span class="title">{{title}}</span>
            <span class="close" @click="destroyVm">x</span>
          </div>
          <div class="biu-alert-text">{{text}}</div>
          <div class="biu-btn-cont">
            <biu-button @click="handelCancel" class="mr-20">{{cancelText}}</biu-button>
            <biu-button @click="handelConfirm">{{confirmText}}</biu-button>
          </div>
        </div>
      </transition>
    </div>
  </transition>
</template>
<script>
import BiuButton from '../../button'
export default {
  name: 'BiuAlert',
  components: { BiuButton },
  data () {
    return {
      title: '',
      text: '',
      promise: null,
      show: false,
      cancelText: '',
      confirmText: ''
    }
  },
  methods: {
    init () { // 初始化, 返回一个promise
      this.show = true
      return new Promise((resolve, reject) => {
        this.promise = { resolve, reject } // 将resolve 、reject暂存起来,方便调用
      })
    },
    handelCancel () { // 取消
      this.promise.reject()
      this.destroyVm()
    },
    handelConfirm () { // 确定
      this.promise.resolve()
      this.destroyVm()
    },
    destroyVm () { // 销毁
      this.show = false
      setTimeout(() => { // 动画完成后执行
        this.$destroy(true) // 完全销毁一个实例。清理它与其它实例的连接,解绑它的全部指令及事件监听器
        this.$el && this.$el.parentNode.removeChild(this.$el) // 从dom节点删除
      }, 500)
    }
  }
}

packages/alert/index.js

import Vue from 'vue'
import alert from './src/alert.vue'

const Alert = Vue.extend(alert) // 创建alert组件的构造类

const alertFun = function (options) { // 接收配置
  let str_num = (typeof options === 'string' || typeof options === 'number')
  const Instance = new Alert({ // 实例化组件
    data: { // 给data的变量赋值
      title: (options && options.title) || '提示',
      text: str_num ? options : ((options && options.text) || ''),
      cancelText: (options && options.cancel) || '取消',
      confirmText: (options && options.confirm) || '确认'
    }
  })
  let vm = Instance.$mount() // 挂载
  document.body.appendChild(vm.$el) // 插入body
  return vm.init() // 执行初始化方法, 返回的是一个promise
}

export default {
  install: (Vue) => { // 暴露install方法供Vue.use()调用
    Vue.prototype.$alert = alertFun // 挂到Vue的原型上使用
  }
}

packages/index.js

/* eslint-disable */
import BiuButton from './button'
import BiuInput from './input'
import BiuAlert from './alert'

const components = {
  BiuButton,
  BiuInput
}

const commonComs = {
  BiuAlert
}

// 两种全局注册组件的方法 vue.use() vue.component() 前提是必须要有一个install()方法
const install = Vue => { // main.js 中使用 Vue.use() 安装全部组件
  if (install.installed) return // 判断是否安装
  install.installed = true // 记录安装状态
  // 遍历公共组件
  Object.keys(commonComs).forEach(key => Vue.use(commonComs[key]))
  // 遍历所有组件
  Object.keys(components).forEach(key => Vue.component(key, components[key]))
}

export default {
  version: '0.1.0',
  install
}

使用方式

main.js

import biuui from '../packages'
Vue.use(biuui)

这样引用是因为我的alert组件写在了组件库中

App.vue

<template>
  <div id="app">
    <h1>biu-ui</h1>
    <biu-button @click="showAlert">show alert</biu-button>
  </div>
</template>

<script>

export default {
  name: 'App',
  methods: {
    showAlert () {
    // 默认配置
      this.$alert('测试alert组件').then(() => {
        console.log('点击了确定')
      }).catch(() => {
        console.log('点击了取消')
      })
    }
  }
}
</script>

自定义配置

this.$alert({
    text: '描述',
    title: '标题',
    cancel: '不',
    comfirm: '好的'}).then(() => {
        console.log('点了好的')
      }).catch(() => {
        console.log('点了不')
      })

到此结束, 记得点赞👍

其他文章:

八步开发一个vue的组件库

图片懒加载之lozad.js

JS的防抖、节流函数

VUE的实现原理(数据劫持、观察者模式)

Javascript实现简单的冒泡排序、插入排序

一个非常简单的-发布订阅模式

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: holdbiu 原文链接:https://juejin.im/post/6844904081085956109

回到顶部