详解用vue编写弹出框组件(2)

<!--template--> <button @click="showAlert">点我</button> <alert ref="alert">我是一个确认框</alert> <!--javascript--> ... methods: { showAlert() { this.$refs.alert.show(); } } ...

当然,如果真要这么用,这个组件还是需要修改一些东西的,比如事件抛出,当点击确定或者取消按钮的时候,需要emit对应的事件,以提供给父组件捕获,并做相应的处理。

动态插入到页面中

为了能让组件动态的插入到页面中,需要对上面的组件进行封装,利用Vue.extend机制,可以轻松的做到这种封装,直接上代码:

import Vue from 'vue'; import alert from './alert'; const AlertConstructor = Vue.extend(alert); const div = document.createElement('div'); AlertConstructor.show = (options) => { document.body.appendChild(div); options.type = 'inform'; const propsData = Object.assign({}, options); const alertInstance = new AlertConstructor({ propsData, }).$mount(div); alertInstance.show(); }; AlertConstructor.confirm = (options) => { document.body.appendChild(div); options.type = 'confirm'; const propsData = Object.assign({}, options); const alertInstance = new AlertConstructor({ propsData, }).$mount(div); alertInstance.show(); }; export default AlertConstructor;

这里,show对应的是通知框,confirm对应的是确认框。我知道这种封装有点简单了,有很多情况没有考虑,比如有多个弹出框时的处理等。这里只是做了简单的封装,为的就是让大家明白此种封装主要思路是什么。

总结

这篇文章仅仅是对自己这几天摸索弹出框组件问题的一个简短的总结与思考。可能还不是很成熟,当做抛砖引玉吧,欢迎大家多多提意见。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfdws.html