this.$refs.one.contentWindow ,这里one如果是变量,怎么可以用变量来表示呢
在 Vue 中,如果你想通过一个变量来动态访问 this.$refs 的元素,你可以使用 this.$refs 的对象语法来实现。具体来说,你可以通过变量来动态访问 this.$refs 中的某个元素。
假设你有多个 iframe 元素,并且需要动态访问其中一个 iframe 的 contentWindow,你可以通过如下方式来实现:
代码示例:
<template>
<div>
<!-- 动态绑定 ref -->
<iframe ref="iframe1" src="https://example.com"></iframe>
<iframe ref="iframe2" src="https://example.com"></iframe>
<!-- 按钮用于触发获取 iframe 的 contentWindow -->
<button @click="getIframeContent('iframe1')">获取 iframe1 内容</button>
<button @click="getIframeContent('iframe2')">获取 iframe2 内容</button>
</div>
</template>
<script>
export default {
methods: {
getIframeContent(iframeRefName) {
// 使用变量来访问 $refs 中的 iframe
const iframe = this.$refs[iframeRefName];
if (iframe) {
const contentWindow = iframe.contentWindow;
console.log(contentWindow); // 在控制台中输出 iframe 的 contentWindow
} else {
console.log('无法找到对应的 iframe');
}
},
},
};
</script>
解释:
- 动态
ref访问:this.$refs是一个对象,其中键是你设置的ref名称,值是 DOM 元素或者组件实例。在这里,我们使用this.$refs[iframeRefName]来动态访问ref名称。 - 方法
getIframeContent:通过传递iframe1或iframe2作为变量来动态访问相应的 iframe,进而访问其contentWindow。
重点:
this.$refs[iframeRefName]可以用动态的iframeRefName来访问ref。contentWindow是对嵌入在iframe中的浏览器窗口对象的引用,允许你访问和操作 iframe 中的内容。
这样,你就能使用变量来动态获取对应 ref 的 contentWindow,无论是在多个 iframe 中,还是根据其他动态的条件来选择。
如果还有其他问题,欢迎继续提问!
相信坚持的力量,日复一日的习惯.

浙公网安备 33010602011771号