国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue組件掛載到全局方法的示例代碼

2024-05-06 15:32:13
字體:
來源:轉載
供稿:網友

在最近的項目中,使用了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下

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 西林县| 淮南市| 三台县| 洛扎县| 庆云县| 苍梧县| 遵化市| 南投市| 白河县| 诸暨市| 澄江县| 兴和县| 靖远县| 吴忠市| 五原县| 安平县| 福建省| 富顺县| 天全县| 东莞市| 北海市| 沛县| 辽中县| 和龙市| 新余市| 清水河县| 大同县| 平南县| 灯塔市| 三原县| 军事| 荆门市| 延长县| 甘肃省| 绥德县| 天柱县| 随州市| 宜丰县| 南木林县| 遂宁市| 贵南县|