我正在尝试创建一个模式库应用程序来显示iframe
元素中的组件,以及它们的HTML。每当iframe
的内容发生变化时,我希望包含iframe
的页面通过重新获取iframe
的HTML并将其打印到页面上来响应。不幸的是,该页面无法知道它的iframe
中的组件何时发生变化。下面是一个简化的设置示例:
我有一个“手风琴”组件,它在更新时发出全球性事件:
components/Accordion.vue
<template>
<div class="accordion"></div>
</template>
<script>
export default {
updated() {
console.log("accordion-updated event emitted");
this.$root.$emit("accordion-updated");
}
}
</script>
然后,我将该组件拉到页面中:
pages/components/accordion.vue
<template>
<accordion/>
</template>
<script>
import Accordion from "~/components/Accordion.vue";
export default {
components: { Accordion }
}
</script>
然后,我在另一个页面的iframe
中显示该页面:
pages/documentation/accordion.vue
<template>
<div>
<p>Here's a live demo of the Accordion component:</p>
<iframe src="/components/accordion"></iframe>
</div>
</template>
<script>
export default {
created() {
this.$root.$on("accordion-updated", () => {
console.log("accordion-updated callback executed");
});
},
beforeDestroy() {
this.$root.$off("accordion-updated");
}
}
</script>
当我编辑"accordion“组件时,”事件发出“日志会出现在我的浏览器的控制台中,因此似乎发出了accordion-updated
事件。不幸的是,我从未看到documentation/accordion
页面中事件处理程序中的“回调执行”控制台日志。我尝试过同时使用this.$root.$emit
/this.$root.$on
和this.$nuxt.$emit
/this.$nuxt.$on
,但两者似乎都不起作用。
是否有可能每个页面包含一个单独的Vue实例,因此iframe
页面的this.$root
对象与documentation/accordion
页面的this.$root
对象不相同?如果是的话,我又如何解决这个问题呢?
发布于 2018-08-13 21:11:47
听起来我是对的,在我的iframe
页面和它的父页面中确实有两个单独的Vue实例:https://forum.vuejs.org/t/eventbus-from-iframe-to-parent/31299
因此,我最终将一个MutationObserver
附加到iframe
上,如下所示:
<template>
<iframe ref="iframe" :src="src" @load="onIframeLoaded"></iframe>
</template>
<script>
export default {
data() {
return { iframeObserver: null }
},
props: {
src: { type: String, required: true }
},
methods: {
onIframeLoaded() {
this.getIframeContent();
this.iframeObserver = new MutationObserver(() => {
window.setTimeout(() => {
this.getIframeContent();
}, 100);
});
this.iframeObserver.observe(this.$refs.iframe.contentDocument, {
attributes: true, childList: true, subtree: true
});
},
getIframeContent() {
const iframe = this.$refs.iframe;
const html = iframe.contentDocument.querySelector("#__layout").innerHTML;
// Print HTML to page
}
},
beforeDestroy() {
if (this.iframeObserver) {
this.iframeObserver.disconnect();
}
}
}
</script>
将观察者直接附加到contentDocument
意味着,除了<head>
之外,当文档的<head>
中的元素发生变化时,事件处理程序也会触发。这允许我在Vue向JavaScript中注入新的CSS或JavaScript块(通过热模块替换)时做出反应。
https://stackoverflow.com/questions/51811305
复制相似问题