在 Vue.js 中,当您尝试使用 $this.$refs.myframe.querySelectorAll() 来在 iframe 元素 myframe 内查找子元素时,可能会遇到 'querySelectorAll is not a function' 错误。这是因为 $this.$refs.myframe 是一个 DOM 元素,而不是一个数组或类数组对象。因此,您不能像数组那样使用 querySelectorAll() 方法。

为了解决这个问题,可以使用以下两种方法:

  1. 使用 myframe 元素的 querySelectorAll() 方法:
const elements = this.$refs.myframe.contentWindow.document.querySelectorAll('.class-name');
  1. 使用 myframe 元素的 contentDocument 属性访问文档对象,并使用 querySelectorAll() 方法:
const elements = this.$refs.myframe.contentDocument.querySelectorAll('.class-name');

请注意,这两种方法都需要在 myframe 元素加载完成后才能使用。您可以在 myframe 元素的 load 事件中使用它们,或者使用 async/awaitPromise 来等待 myframe 元素加载完成。

例如,您可以在 myframe 元素的 load 事件中使用以下代码:

this.$refs.myframe.addEventListener('load', () => {
  // 在 iframe 加载完成后使用 querySelectorAll() 方法
  const elements = this.$refs.myframe.contentWindow.document.querySelectorAll('.class-name');
  // 您的代码
});

通过以上方法,您可以轻松地解决 $this.$refs.myframe.querySelectorAll is not a function 错误,并成功地在 iframe 元素中查找子元素。

Vue.js 中解决 '$this.$refs.myframe.querySelectorAll is not a function' 错误

原文地址: https://www.cveoy.top/t/topic/mKOZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录