最近在重构公司的项目,有些组件想要封装的更灵活,例如toast、loading、messageBox等弹窗组件,模仿了mint-ui封装此类组件的方式封装了自己的弹窗组件;
mint-UI的toast、loading、messageBox等弹窗组件基于Vue.extend()方法,也就是预设了部分选项的Vue实例构造器,返回一个组件构造器;用来生成组件,可以在实例上扩展方法,从而使用更灵活;可以理解为当在模版中遇到该组件名称作为标签的自定义元素时,会自动调用这个实例构造器来生成组件实例,并挂载到指定元素上。
一、Vue.extend(options)简单的使用:(主要用于需要 动态渲染的组件,或者类似于window.alert() 提示组件)
注意:extend创建的是一个组件构造器,而不是一个具体的组件实例;
属于 Vue 的全局 API,在实际业务开发中我们很少使用,因为相比常用的 Vue.component 写法使用 extend 步骤要更加繁琐一些。但是在一些独立组件开发场景中,Vue.extend + $mount 这对组合是我们需要去关注的。
基础用法:
<div id="mount-point"></div>// 创建构造器var Profile = Vue.extend({ template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White', alias: 'Heisenberg' } }})// 创建 Profile 实例,并挂载到一个元素上。new Profile().$mount('#mount-point')
可以看到,extend 创建的是 Vue 构造器,而不是我们平时常写的组件实例,所以不可以通过 new Vue({ components: testExtend }) 来直接使用,需要通过 new Profile().$mount('#mount-point') 来挂载到指定的元素上。
第二种写法,可以在创建实例的时候传入一个元素,生成的组件将会挂载到这个元素上,跟$mount差不多,如下:
1、定义一个vue模版:
let tem ={ template:'{{firstName}} {{lastName}} aka {{alias}}', data:function(){ return{ firstName:'Walter', lastName:'White', alias:'Heisenberg' }}
2 、调用;
const TemConstructor = Vue.extend(tem) const intance = new TemConstructor({el:"#app"}) //生成一个实例,并且挂载在#app上
二、封装toast组件
首先按照普通写法定义一个vue组件模版,toast.vue,写法与普通组件写法相同;
然后重点来了,看一下怎么具体挂载到vue组件上的
const ToastConstructor = Vue.extend(toast) // toast就是vue模版let toastTool = []const getIntance = () => {// 通过构造器获取实例 if (toastTool.length > 0) { const intance = toastTool[0] return intance } return new ToastConstructor({ el: document.createElement('div') })}const removeDom = (e) => { if (e.target.parentNode) { e.target.parentNode.removeChild(e.target) }}ToastConstructor.prototype.close = function () { // 实例的一些方法 this.visible = false this.closed = true this.$el.addEventListener('transitionend', removeDom) // 执行完毕之后删除dom toastTool.push(this) console.log(toastTool)}const Toast = (options = {}) => { // options是对应的props需要接收的传入的值 const intance = getIntance() document.body.appendChild(intance.$el) // 将元素append到页面上 intance.message = typeof options !== 'object' ? options : options.message || '操作成功' intance.duration = options.duration || 3000 intance.className = options.className || '' intance.iconName = options.iconName || '' intance.position = options.position || '' intance.closed = false intance.$el.removeEventListener('transitionend', removeDom) clearTimeout(intance.timer) Vue.nextTick(function () { intance.visible = true intance.duration && (intance.timer = setTimeout(function () { if (intance.closed) { return false } intance.close() }, intance.duration)) }) return intance}export default Toast //将Toast方法导出,调用
将Toast方法导出,将这个方法挂载到vue全局变量
Vue.$toast = Vue.prototype.$toast = Toast
Vue.$loading = Vue.prototype.$loading = Loading
在项目中使用时就可以直接用this.$toast()调用,或者Vue.$toast()调用,返回的是一个instance,创建了一个组件。
主要对Vue.extend的用法,主要用于动态渲染组件和一个类似于似于 window.alert() 提示组件