全局弹窗 - vue2

296 阅读1分钟

业务需要封装自定义全局弹窗

我的方法的核心点

  1. 在自己的组件文件夹的index.js中将需要全局使用的组件通过Vue安装插件的方式挂载并暴露。
// 通用操作按钮点击后 弹框
import MyPopup from './popup/index.vue'

export const WyxComponents = {
    install(Vue) {
        Vue.component('MyPopup', MyPopup)
    }
}
  1. 在main.js中引入并use一下(全局使用)
import { MyComponents } from './components/index';
Vue.use(MyComponents)
  1. 在App.js中使用组件,通过ref挂在Vue原型上(将组件注册为全局方法)
import Vue from 'vue';
import { MyPopup } from './components/index'
export default {
  components: { MyPopup },
  mounted() {
    Vue.prototype.$popup = this.$refs.popup
  }
}

组件中我使用的一些知识点

  • 参数注释:@param { 变量类型 } 变量名 变量初始值/默认值
  • ES6对象的解构赋值:const { 原对象中的键名:自己取的别名 } = 原对象
  • 显式转换为字符串:String( 变量名 )
  • 遍历获取对象键名组成的数组(返回值为数组。)Object.keys( 对象 )