继上次搭完一个组件库的基本框架, 今天再来实现一个通用组件(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样式的
先附上代码, 组件中的样式和动画部分就省略了,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) } } } 复制代码
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的原型上使用 } } 复制代码