注意,由于跨域的安全限制,只能访问同源的 iframe 内容。如果 iframe 的源与父组件的源不同,那么在访问其内容时可能会遇到跨域错误。
<template><div><iframe ref="myIframe" src="https://example.com" @load="handleLoad"></iframe></div>
</template><script>
export default {methods: {handleLoad() {const iframe = this.$refs.myIframe; // 获取 iframe 元素const iframeContent = iframe.contentWindow || iframe.contentDocument; // 获取 iframe 的内容窗口或文档对象if (iframeContent) {const targetElement = iframeContent.document.getElementById('targetElementId'); // 使用标准的 DOM 操作方法获取目标元素console.log(targetElement); // 打印目标元素到控制台}}}
};
</script>