掌握使用postMessage传递数据

在不同的项目中,如果有组件交互除了微前端,我们就得使用iframe来嵌套在页面上,交互效果不免出现数据传递,这时候我们使用postMessage是一个不错的方法

子组件:点击给父组件传递数据

<template>
  <div>
    <h1>Child Component</h1>
    <button @click="sendMessage">Send Message to Parent</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendMessage() {
      const message = 'Hello from child component!';
      window.parent.postMessage(message, '*');
    }
  }
};
</script>

父组件:接收处理来自子组件的数据

<template>
  <div>
    <h1>Parent Component</h1>
    <iframe ref="childIframe" src="child.html"></iframe>
  </div>
</template>
<script>
export default {
  mounted() {
    const childIframe = this.$refs.childIframe;
    childIframe.addEventListener('message', this.receiveMessage);
  },
  beforeDestroy() {
    const childIframe = this.$refs.childIframe;
    childIframe.removeEventListener('message', this.receiveMessage);
  },
  methods: {
    receiveMessage(event) {
      if (event.origin !== window.location.origin) return;
      console.log('Received message from child:', event.data);
      // 处理来自子组件的消息
    }
  }
};
</script>

子组件如果在初始化时用到父组件中的数据,父组件可以使用src携带参数传递,子组件用$route来获取,当父组件数据发生改变iframe可以跟着重新加载

  watch: {
    'global.language.active': function (val) {
      const iframe = document.getElementById('iframe');
      iframe.src = '';
      //使用$nextTick或者setTimeout都行
      setTimeout(() => {
        iframe.src = `https:/xxxxxx.com/xx/xx/xxx?type=${global.search.type}&value=${global.search.value}&iniframe=true&language=${val}`;
      }, 0);
    }
  },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值