uni-app中通过ref拿子对象并执行对象上的方法写法太麻烦了

uni-app中通过ref拿子对象并执行对象上的方法写法太麻烦了

开发环境 版本号 项目创建方式
Windows win10 HBuilderX

操作步骤:

```javascript
this.$refs.funcReal.$refs.uDropdown.close();

预期结果:

理想的写法:  `this.$refs.funcReal.uDropdown.close();`

### 实际结果:

只能逐级拿


### bug描述:
子对象refFuncReal上有个组件,组件上边有个close方法 ,ref属性uDropdown  
父级对象index,里边放funcReal, ref属性funcReal  
父级上边要执行子对象funcReal上ref控件的close方法  

写法1:  
//通过ref拿到当前菜单下的funcReal对象  
var objParent=this.$refs.funcReal;  
// 通过当前对象拿到uDropdown对象  
var objChild=objParent.$refs.uDropdown;  
//执行uDropdown下的方法  
objChild.close();  

写法2:  
`this.$refs.funcReal.$refs.uDropdown.close();`  

这个需要改进下:  
应该直接从当前节点开始直接点起走就完事了  
理想的写法:  `this.$refs.funcReal.uDropdown.close();`  
目前这种写法不行,只能逐级拿。

更多关于uni-app中通过ref拿子对象并执行对象上的方法写法太麻烦了的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app中通过ref拿子对象并执行对象上的方法写法太麻烦了的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中,ref的访问机制确实是层级式的,这是Vue的设计规范。要简化调用可以尝试以下方案:

  1. 使用计算属性缓存引用:
computed: {
  uDropdown() {
    return this.$refs.funcReal?.$refs.uDropdown
  }
}
// 调用:this.uDropdown.close()
  1. 在子组件中暴露方法:
// 子组件funcReal中
methods: {
  closeDropdown() {
    this.$refs.uDropdown.close()
  }
}
// 父组件调用:this.$refs.funcReal.closeDropdown()
  1. 使用事件通信代替直接调用:
// 子组件触发事件
this.$emit('close-dropdown')
// 父组件监听处理
回到顶部