Vue.js 报错:'Uncaught (in promise) TypeError: _this.$refs.myFrame.querySelectorAll is not a function' 解决方法
在 Vue.js 开发中,经常会遇到 'Uncaught (in promise) TypeError: _this.$refs.myFrame.querySelectorAll is not a function' 的错误。这个错误表示在使用 $refs 对象的 myFrame 属性时,尝试调用其 querySelectorAll 方法,但该方法不存在。
可能的原因是:
myFrame不是一个 DOM 元素。myFrame是一个 DOM 元素,但没有实现querySelectorAll方法。
解决方法:
- 检查
myFrame属性: 确保myFrame属性指向的是一个 DOM 元素。可以使用console.log(_this.$refs.myFrame)查看其类型和属性。 - 使用
contentWindow: 如果myFrame是一个<iframe>元素,可以使用myFrame.contentWindow.document.querySelectorAll来代替myFrame.querySelectorAll。
示例代码:
<template>
<iframe ref='myFrame' src='https://www.example.com'></iframe>
</template>
<script>
export default {
mounted() {
// 获取 iframe 内部页面的所有 <p> 元素
const paragraphs = this.$refs.myFrame.contentWindow.document.querySelectorAll('p');
console.log(paragraphs);
}
}
</script>
通过以上步骤,可以有效地解决 'Uncaught (in promise) TypeError: _this.$refs.myFrame.querySelectorAll is not a function' 的错误。
原文地址: https://www.cveoy.top/t/topic/mv0h 著作权归作者所有。请勿转载和采集!