vue.extend解决vue页面转构造函数暴露js供全局使用

发布于:2024-06-21 ⋅ 阅读:(108) ⋅ 点赞:(0)

 用途: 解决在一些微前端项目中, B工程使用A工程的弹窗代码

// MaterialListPlugin.js文件, 在项目入口引入
// eg: 在main.js中添加一行 import '@/components/MaterialListPlugin.js'

import Vue from 'vue'
import MaterialListPlugin from '@/components/MaterialListPlugin.vue' // 简单的弹窗示例

function showDialog(options) {
  const Dialog = Vue.extend(MaterialListPlugin)
  const app = new Dialog().$mount(document.createElement('div'))

  // options:{} 绑定this中的属性
  for (const key in options) {
    app[key] = options[key]
  }
  document.body.appendChild(app.$el) //注入html
  return app // 返回实例以供页面调用
}

Vue.prototype.$MyMaterial = showDialog

页面调用: this.$MyMaterial().onShow() // onShow是vue页面的方法, 唤起弹窗的

// MaterialListPlugin.vue文件 (简单的弹窗示例)
<template>
  <my-dialog :visible="dialogShow">
    <div class="my-dialog-content">
        // 弹窗内容
    </div>
    <template v-slot:footer>
        <t-button @click="onHide">取消</t-button>
        <t-button @click="onConfirm">确认</t-button>
    </template>
  </my-dialog>
</template>

<script>
export default {
  name: 'materialWordPlugin',
  data() {
    return {
      dialogShow: false,
    }
  },
  methods: {
    // 弹窗显示
    onShow() {
      this.dialogShow = true
    },
    // 弹窗隐藏
    onHide() {
      this.dialogShow = false
    },
    // 确定按钮
    onConfirm() {
      this.onHide()
    },
  },
}
</script>

参考: Vue中Vue.extend()的使用及解析_vue.js_脚本之家


网站公告

今日签到

点亮在社区的每一天
去签到