aspack001
aspack001
  • 发布:2025-09-09 22:45
  • 更新:2025-09-09 22:45
  • 阅读:16

如何查找当前页面是否有指定组件(含嵌套)

分类:uni-app

我有很多页面都用到了组件A(可能嵌套比较深),我有个定时器需要判断如果当前页面下面包含子组件或者孙子组件A,则停止某个任务。

vue是可以用下面代码遍历的,但是在uniapp中,vm根本没有$children属性。这样我就没法用下面的办法来实现我的目的。

求大神解答,谢谢!

function findComponent(vm, name) {  
  let found = null  
  vm.$children.forEach(child => {  
    if (child.$options.name === name) {  
      found = child  
    } else {  
      const res = findComponent(child, name)  
      if (res) found = res  
    }  
  })  
  return found  
}  

// 用法  
let pages = getCurrentPages()  
let page = pages[pages.length - 1].$vm  
let comp = findComponent(page, 'aspack-sound') // 这里的名字是组件定义里的 name  
if (comp) {  
  console.log('组件存在')  
} else {  
  console.log('组件不存在')  
}  
2025-09-09 22:45 负责人:无 分享
已邀请:

要回复问题请先登录注册