項目中如果很多地方用到同一個模態框組件,每次在頁面中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()
})
調用方法的時候,裏面傳值可根據你的需求進行傳值,這裏只是個例子,給大家個思路。下次再來講封裝的另一種方法,想知道的朋友們可以看我們的開源項目。