在最近的項目中,使用了bootstrap-vue來開發,然而在實際的開發過程中卻發現這個UI提供的組件并不能打到我們預期的效果,像alert、modal等組件每個頁面引入就得重復引入,并不像element那樣可以通過this.$xxx來調用,那么問題來了,如何通過this.$xxx來調用起我們定義的組件或對我們所使用的UI框架的組件呢。
以bootstrap-vue中的Alert組件為例,分一下幾步進行:
1、定義一個vue文件實現對原組件的再次封裝
main.vue
<template> <b-alert class="alert-wrap pt-4 pb-4" :show="isAutoClose" :variant="type" dismissible :fade="true" @dismiss-count-down="countDownChanged" @dismissed="dismiss" > {{msg}} </b-alert></template><script>export default { /** * 參考: https://bootstrap-vue.js.org/docs/components/alert * @param {string|number} msg 彈框內容 * @param {tstring} type 彈出框類型 對應bootstrap-vue中variant 可選值有:'primary'、'secondary'、'success'、'danger'、'warning'、'info'、'light'、'dark'默認值為 'info' * @param {boolean} autoClose 是否自動關閉彈出框 * @param {number} duration 彈出框存在時間(單位:秒) * @param {function} closed 彈出框關閉,手動及自動關閉都會觸發 */ props: { msg: { type: [String, Number], default: '' }, type: { type: String, default: 'info' }, autoClose: { type: Boolean, default: true }, duration: { type: Number, default: 3 }, closed: { type: Function, default: null } }, methods: { dismiss () { this.duration = 0 }, countDownChanged (duration) { this.duration = duration } }, computed: { isAutoClose () { if (this.autoClose) { return this.duration } else { return true } } }, watch: { duration () { if (this.duration === 0) { if (this.closed) this.closed() } } }}</script><style scoped>.alert-wrap { position: fixed; width: 600px; top: 80px; left: 50%; margin-left: -200px; z-index: 2000; font-size: 1.5rem;}</style>這里主要就是對組件參數、回調事件的一些處理,與其他處理組件的情況沒有什么區別
2、定義一個js文件掛載到Vue上,并和我們定義的組件進行交互
index.js
import Alert from './main.vue'import Vue from 'vue'let AlertConstructor = Vue.extend(Alert)let instancelet seed = 1let index = 2000const install = () => { Object.defineProperty(Vue.prototype, '$alert', { get () { let id = 'message_' + seed++ const alertMsg = options => { instance = new AlertConstructor({ propsData: options }) index++ instance.id = id instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.$el.style.zIndex = index return instance.vm } return alertMsg } })}export default install其主要思想是通過調用這個方法給組件傳值,然后append到body下
新聞熱點
疑難解答
圖片精選