在iframe中找到指定组件,并使用内部方法,应对业务需求使用
window挂载vue实例
在
app.js
或main.js
中挂载vue
实例到window
let v = new Vue({
router,
store,
render: function (h) { return h(App) }
}).$mount('#app')
window.VUE = v
在iframe中实现查找组件方法
递归实例查找到对应组件,通过组件的
ref
实现
该方法通过传入ref
的名称来进行对应查找组件
查找的组件最外层需要绑定ref
// 定义一个函数 isComponents,用于在数据结构中查找包含特定键的容器
function isComponents(data, key) {
// 检查传入的数据是否不是数组且长度为0,如果是则直接返回undefined
if (!Array.isArray(data) && !data.length) return;
// 遍历数据数组中的每一个元素
for (const item of data) {
// 检查当前元素是否包含$refs属性,并且该属性中包含指定的键
if (item.$refs && key in item.$refs) {
// 如果条件满足,返回当前元素
return item;
}
// 检查当前元素是否包含$children属性且其长度大于0
if (item.$children?.length) {
// 如果条件满足,递归调用isPdfContainer函数,继续在子元素中查找
return isComponents(item.$children, key);
}
}
}
vue组件中的对应配置
组件最外层绑定ref名称,用于上面的方法进行查找对应组件
<template>
<div ref="pdfContainer">
<iframe width="100%" height="500px" scrolling="no" id="ifs" :src="getPdfViewSrc"></iframe>
</div>
</template>
<script>
export default {
name: "test",
data() {
return {
url: '/static/test.pdf' //设置文档地址
}
},
computed: {
getPdfViewSrc() {
return `/static/pdf/web/viewer.html?disableworker=false&file=${this.url}`
}
},
methods: {
renderedHandler() {
console.log("iframe中调用实例方法,渲染完成")
},
errorHandler() {
console.log("渲染失败")
}
}
}
</script>
iframe中使用
通过iframe中的点击触发查找方法,找到组件后,调用对应方法
<html>
<a href="javascript:;" onclick="download()"></a>
<body>
<script>
function download() {
//查找到对应的组件 传入挂载的vue实例下的组件数组,递归查找到对应的组件并返回
let item = isComponents(window.parent.VUE.$children, 'pdfContainer')
// 调用组件上的方法
item.renderedHandler()
}
</script>
</body>
</html>