vue父系统页面中通过iframe嵌套原生html子系统,子系统调用父系统的el-dialog关闭方法

422 阅读1分钟

昨天做项目,遇到的难点,记录一下!第一次写!!!

vue父系统

vue html--这里的弹框是封装了的,主要是@handleClose="handleClose"方法

<template>
  <contact-dialog
    dialogwidth="70%"
    :dialogTitle="dialogTitle"
    :dialogVisible="dialogVisible"
    @handleClose="handleClose"
  >
    <template slot="public-model-content">
      <div class="control-container">
        <iframe
          :src="mesUrl"
          style="width: 100%;height: 100%;"
        ></iframe>
      </div>
    </template>
  </contact-dialog>
</template>

vue mounted钩子函数

// 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    // 这里是进入这个弹框页面 通过url给子系统传参的,用于子系统登录
    const userName = getUserNameCookie()
    const userPassword = "123456"
    const uid = this.$props.personId
    const token = getSsoToken()
    this.mesUrl = "http://127.0.0.1:8848/web_im/index.html?userName="+userName
      +"&userPassword="+userPassword+"&personId="+uid+"&token="+token;

   
    // 这里是关键代码 是子系统触发父系统的监听函数
    const _than = this
    window.addEventListener('message', e => {
      // e.data为子页面发送的数据
      // 判断 type 为callChildFn才调用弹框关闭方法
      if(e.data.type == "callChildFn") {
        _than.handleClose()
      }
    })
  },

vue methods方法集合体

methods: {
    // 弹框 叉号
    handleClose(done) {
      this.$emit('handleClose',done)
    },
},

原生子系统,使用的layui的提示框

layui.layer.open({
    title: false,
    closeBtn: 0,
    btnAlign: 'c',
    skin: 'my-skin',
    content: '<div style="text-align:center;">你已在异地登录!</div>',
    yes: function(index, layero){
	// 给父系统发送消息
	window.parent.postMessage({
            type: 'callChildFn',
            data: 'data from parent'
	}, '*');			
        layui.layer.close(index);
    }
});

其实关键代码就是window.parent.postMessage