layui.open 使用postMessage父子页面传值 基于jq+layui和vue

项目环境是由jq+layui组成的父页面和vue写的子页面

要求:1.在从父页面打开子页面的同时将接口数据传递给子页面。

2.在子页面打开时渲染数据并在其操作完成提交后关闭当前子页面。

ps:在open 子页面的iframe标签下使用parent.xxx,layer.getChildFrame('body', index);等会导致跨域问题。Blocked a frame with origin "null" from accessing a cross-origin frame.


 父传子

因为父页面的框架就是使用jq+layui,所以在实现打开子页面时用到了layer.open,在其success回调中使用document.getElementById('Optimize_iframe').contentWindow.postMessage(res,"*"),且一定要加入iframe.onload 避免发送数据和接收数据出现偏差。代码如下:

 父页面:

 let url = '<iframe src="../productOptimize/productOptimize.html" id="Optimize_iframe" width="100%" height="100%" frameborder="0"></iframe>'
            $('#cancel').click(function () {
              //在全局中var optimizeProduct 方便后续的子页面返回数据关闭
              optimizeProduct = layer.open({
                type: 1,
                area: ['100%', '100%'],
                resize: false,
                title:'智能优化',
                content: url,//这种方式方便在iframe标签中加入id
                success: function (layero, index) {
                  var iframe = document.getElementById('Optimize_iframe')
                  //一定要有onload,等待加载结束
                  iframe.onload = function() {
                    //res为接口返回数据
                    document.getElementById('Optimize_iframe').contentWindow.postMessage(res,'*')
                  }
                },
              })
            })

 ps如果使用type:2,content:为项目内文件的时候,默认打开的iframe标签的id是有个默认值的,从开发者工具里找

基于vue的子页面可以在mounted中接收父页面的传值 

 子页面接收:

    mounted () {
      this.$nextTick(()=>{
      window.addEventListener('message', e => {
              console.log(e);
        })
      })
    },

子传父

场景是子页面进行完成操作后,点击提交按钮,接口返回success,执行父页面layer.close()方法关闭子页面。

 子页面:

js.xxxx((res)=>{//接口数据
          res = JSON.parse(res)
          console.log(res);
          if(res.success){
            window.parent.postMessage(
            {
              data: {
                code: "success",
                test: "我是子页面数据",
              },
            },
            "*"
          );
          }else{
            this.$message.error(res.error)
          }
     },paramsdata)

父页面接收:

window.addEventListener('message', e => {
  // e.data为子页面发送的数据
  layer.close(optimizeProduct);
  console.log(e.data)
})

未解决:在使用

    var body = layer.getChildFrame('body', index);
    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象,执行iframe页的方法:iframeWin.method();
    console.log(body.html()) //得到iframe页的body内容
    body.find('input').val('Hi,我是从父页来的')

以及子页面在使用parent.xxxx时出现的跨域问题

猜你喜欢

转载自blog.csdn.net/weixin_42574985/article/details/131068218