项目中如果很多地方用到同一个模态框组件,每次在页面中import引用是不是很麻烦?现在教大家一种很方便的封装方法,只需调用js方法就可以实现。废话不说,先上图讲下整体流程,会把代码贴出来。
1.先写好你用的组件。根据业务不同组件不同,这里只是我们项目中的文件。
2.新建js文件,这里是我建的js文件。
可以直接使用element中封装的$msgbox方法,h标签中引用组件名称,props里面可以放组件中的传值,on方法里面调用回调函数。
噔噔噔,给大家贴代码了!!!自己写的组件就不贴了,里面是项目中的业务。
modal-attr.js文件
export default function modalAttr(val, callback, keyNum) {
const h = this.$createElement
return new Promise((resolve, reject) => {
this.$msgbox({
title: '属性规格',
customClass: 'upload-form',
closeOnClickModal: false,
showClose: false,
message: h('div', { class: 'common-form-upload' }, [
h('attrFrom', {
props: {
currentRow: val,
keyNum: keyNum
},
on: {
getList() {
callback()
}
}
})
]),
showCancelButton: false,
showConfirmButton: false
}).then(() => {
resolve()
}).catch(() => {
reject()
this.$message({
type: 'info',
message: '已取消'
})
})
})
}
接下来要在main.js中全局注册使用。
import attrFrom from './components/attrFrom'
Vue.component('attrFrom', attrFrom)
这样就可以全局使用拉~~~~
使用方法:
this.$modalAttr(this.formDynamics, function() {
_this.productGetRule()
})
调用方法的时候,里面传值可根据你的需求进行传值,这里只是个例子,给大家个思路。下次再来讲封装的另一种方法,想知道的朋友们可以看我们的开源项目。