vue组件挂载到全局方法的示例代码


Posted in Javascript onAugust 02, 2018

在最近的项目中,使用了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 instance
let seed = 1
let index = 2000
const 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下

3、最后需要在main.js中use一下

import Alert from '@/components/alert/index'
Vue.use(Alert)

4、使用

this.$alert({msg: '欢迎━(*`∀´*)ノ亻!'})

5、confrim的封装也是一样的

main.vue

<template>
 <b-modal
  v-if="!destroy"
  v-model="isShow"
  title="温馨提示"
  @change="modalChange"
  @show="modalShow"
  @shown="modalShown"
  @hide="modalHide"
  @hidden="modalHidden"
  @ok="modalOk"
  @cancel="modalCancel"
  :centered="true"
  :hide-header-close="hideHeaderClose"
  :no-close-on-backdrop="noCloseOnBackdrop"
  :no-close-on-esc="noCloseOnEsc"
  :cancel-title="cancelTitle"
  :ok-title="okTitle">
   <p class="my-4">{{msg}}</p>
 </b-modal>
</template>
<script>
export default {
 /**
  * 参考: https://bootstrap-vue.js.org/docs/components/modal
  * @param {boolean} isShow 是否显示modal框
  * @param {string|number} msg 展示内容
  * @param {boolean} hideHeaderClose 是否展示右上角关闭按钮 默认展示
  * @param {string} cancelTitle 取消按钮文字
  * @param {string} okTitle 确定按钮文字
  * @param {boolean} noCloseOnBackdrop 能否通过点击外部区域关闭弹框
  * @param {boolean} noCloseOnEsc 能否通过键盘Esc按键关闭弹框
  * @param {function} change 事件触发顺序: show -> change -> shown -> cancel | ok -> hide -> change -> hidden
  * @param {function} show before modal is shown
  * @param {function} shown modal is shown
  * @param {function} hide before modal has hidden
  * @param {function} hidden after modal is hidden
  * @param {function} ok 点击'确定'按钮
  * @param {function} cancel 点击'取消'按钮
  * @param {Boolean} destroy 组件是否销毁 在官方并没有找到手动销毁组件的方法,只能通过v-if来实现
  */
 props: {
  isShow: {
   type: Boolean,
   default: true
  },
  msg: {
   type: [String, Number],
   default: ''
  },
  hideHeaderClose: {
   type: Boolean,
   default: false
  },
  cancelTitle: {
   type: String,
   default: '取消'
  },
  okTitle: {
   type: String,
   default: '确定'
  },
  noCloseOnBackdrop: {
   type: Boolean,
   default: true
  },
  noCloseOnEsc: {
   type: Boolean,
   default: true
  },
  change: {
   type: Function,
   default: null
  },
  show: {
   type: Function,
   default: null
  },
  shown: {
   type: Function,
   default: null
  },
  hide: {
   type: Function,
   default: null
  },
  hidden: {
   type: Function,
   default: null
  },
  ok: {
   type: Function,
   default: null
  },
  cancel: {
   type: Function,
   default: null
  },
  destroy: {
   type: Boolean,
   default: false
  }
 },
 methods: {
  modalChange () {
   if (this.change) this.change()
  },
  modalShow () {
   if (this.show) this.show()
  },
  modalShown () {
   if (this.shown) this.shown()
  },
  modalHide () {
   if (this.hide) this.hide()
  },
  modalHidden () {
   if (this.hidden) this.hidden()
   this.destroy = true
  },
  modalOk () {
   if (this.ok) this.ok()
  },
  modalCancel () {
   if (this.cancel) this.cancel()
  }
 }
}
</script>

index.js 

import Confirm from './main.vue'
import Vue from 'vue'
let ConfirmConstructor = Vue.extend(Confirm)
let instance
let seed = 1
let index = 1000
const install = () => {
 Object.defineProperty(Vue.prototype, '$confirm', {
  get () {
   let id = 'message_' + seed++
   const confirmMsg = options => {
    instance = new ConfirmConstructor({
     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 confirmMsg
  }
 })
}
export default install

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript转换字符串为dom对象(字符串动态创建dom)
May 10 Javascript
基于Jquery的实现回车键Enter切换焦点
Sep 14 Javascript
推荐17个优美新鲜的jQuery的工具提示插件
Sep 14 Javascript
Js制作简单弹出层DIV在页面居中 中间显示遮罩的具体方法
Aug 08 Javascript
分享33个jQuery与CSS3实现的绚丽鼠标悬停效果
Dec 15 Javascript
js实现刷新iframe的方法汇总
Apr 27 Javascript
jQuery实现鼠标经过图片变亮其他变暗效果
May 08 Javascript
javascript使用输出语句实现网页特效代码
Aug 06 Javascript
基于JavaScript实现根据手机定位获取当前具体位置(X省X市X县X街道X号)
Dec 29 Javascript
vue基于Element构建自定义树的示例代码
Sep 19 Javascript
JS中注入eval, Function等系统函数截获动态代码
Apr 03 Javascript
JavaScript实现轮播图效果
Oct 30 Javascript
原生js封装的ajax方法示例
Aug 02 #Javascript
JS实现根据指定值删除数组中的元素操作示例
Aug 02 #Javascript
详解Angular中通过$location获取地址栏的参数
Aug 02 #Javascript
JavaScript防止全局变量污染的方法总结
Aug 02 #Javascript
微信小程序之自定义组件的实现代码(附源码)
Aug 02 #Javascript
Array数组对象中的forEach、map、filter及reduce详析
Aug 02 #Javascript
利用Blob进行文件上传的完整步骤
Aug 02 #Javascript
You might like
简体中文转换为繁体中文的PHP函数
2006/10/09 PHP
PHP中的Session对象如何使用
2015/09/25 PHP
asp(javascript)全角半角转换代码 dbc2sbc
2009/08/06 Javascript
通过jquery的$.getJSON做一个跨域ajax请求试验
2011/05/03 Javascript
javascript中日期转换成时间戳的小例子
2013/03/21 Javascript
jQuery学习笔记(4)--Jquery中获取table中某列值的具体思路
2013/04/10 Javascript
什么是Node.js?Node.js详细介绍
2014/06/01 Javascript
jQuery简单实现页面元素置顶时悬浮效果示例
2016/08/01 Javascript
通过JS和PHP两种方法判断用户请求时使用的浏览器类型
2016/09/01 Javascript
微信小程序 前端源码逻辑和工作流详解
2016/10/08 Javascript
JS 滚动事件window.onscroll与position:fixed写兼容IE6的回到顶部组件
2016/10/10 Javascript
用nodejs搭建websocket服务器
2017/01/23 NodeJs
js学习总结之DOM2兼容处理重复问题的解决方法
2017/07/27 Javascript
通过fastclick源码分析彻底解决tap“点透”
2017/12/24 Javascript
使用socket.io实现简单聊天室案例
2018/01/02 Javascript
layui table数据修改的回显方法
2019/09/04 Javascript
[02:32]DOTA2亚洲邀请赛 C9战队出场宣传片
2015/02/07 DOTA
Python中的time模块与datetime模块用法总结
2016/06/30 Python
学习Python selenium自动化网页抓取器
2018/01/20 Python
解决python中用matplotlib画多幅图时出现图形部分重叠的问题
2019/07/07 Python
numpy np.newaxis 的实用分享
2019/11/30 Python
浅析python标准库中的glob
2020/03/13 Python
Python图像读写方法对比
2020/11/16 Python
使用pandas实现筛选出指定列值所对应的行
2020/12/13 Python
django inspectdb 操作已有数据库数据的使用步骤
2021/02/07 Python
一款css实现的鼠标经过按钮的特效
2014/09/11 HTML / CSS
详解CSS3的box-shadow属性制作边框阴影效果的方法
2016/05/10 HTML / CSS
Html5 Canvas动画基础碰撞检测的实现
2018/12/06 HTML / CSS
美国电视购物HSN官网:HSN
2016/09/07 全球购物
ECCO爱步加拿大官网:北欧丹麦鞋履及皮具品牌
2017/07/08 全球购物
数据库面试要点基本概念
2013/10/31 面试题
药学专业个人自我评价
2013/11/11 职场文书
反邪教宣传工作方案
2014/05/07 职场文书
五四青年节演讲稿
2014/05/26 职场文书
会议承办单位欢迎词
2015/09/30 职场文书
《狼王梦》读后感:可怜天下父母心
2019/11/01 职场文书