vue3+taro中父组件调用子组件的方法(原生小程序selectComponent的替换方案->ref)

665 阅读1分钟

1.业务需求

在父组件A中使用了多个子组件B,A中切换查询条件,将查询的数据通过调用每个子组件B的showAllData方法渲染出来

父组件A中页面结构如下:

     <view class="table">
        <b id="b1"  title="第一季度"></b>
        <b id="b2"  title="第二季度"></b>
      </view>

思路1: 使用taro官网提供的方案

import { getCurrentInstance } from '@tarojs/taro'  
  
const { page } = getCurrentInstance()  
const b1 = page.selectComponent('#b1')

这个需要注意getCurrentInstance的调用时机

最终方案:思路2:使用ref

父组件A

     <view class="table">
        <b ref="b1"  title="第一季度"></b>
        <b ref="b2"  title="第二季度"></b>
      </view>
    import {ref} from 'vue';
    import b from '@/components/b/b';
    const b1 =  ref();
    const b2 =  ref();
    function changeSelectTime(){
        setTimeout(()=>{
            b1.value & b1.value.showAllData();
            b2.value & b2.value.showAllData();
           },0)
    }

子组件B

   function showAllData(){
        console.log('此处为具体的业务代码');
    }
   defineExpose({
       showAllData
   })