index.vue 858 B

12345678910111213141516171819202122232425262728293031323334
  1. <template>
  2. <div>
  3. <el-input v-model="message" style="width: 240px"></el-input>
  4. <el-button @click="postMessage">发送消息给父窗口</el-button>
  5. <p>来自父级的消息: {{ iframeMessage }}</p>
  6. </div>
  7. </template>
  8. <script setup lang="ts" name="testIframe">
  9. import { onMounted, ref, onBeforeUnmount } from "vue";
  10. const message = ref("");
  11. const postMessage = () => {
  12. window.parent.postMessage(
  13. {
  14. type: "FROM_CHILD",
  15. data: message.value,
  16. },
  17. "*"
  18. );
  19. };
  20. const handleMessage = (event) => {
  21. if (event.data.type === "FROM_PARENT") {
  22. iframeMessage.value = event.data.data;
  23. }
  24. };
  25. const iframeMessage = ref("");
  26. onMounted(() => {
  27. window.addEventListener("message", handleMessage);
  28. });
  29. onBeforeUnmount(() => {
  30. window.removeEventListener("message", handleMessage);
  31. });
  32. </script>
  33. <style scoped lang="scss"></style>