vue3项目,通过defineComponent创建的组件,在父组件中想通过ref拿到该组件内部的方法,从控制台看,ref对象中没有相关属性,这是为什么,正确要怎么做?

作者站长头像
站长
· 阅读数 13

子组件内容:

const CesiumMap = defineComponent<Props>((props, { slots, emit, attrs }) => {
  // 要在父组件访问setMapInfo这个方法
  const setMapInfo = () => {
    // TODO
  };

  return () => {
    return (
      <div class="tsd-mapContainer">
        子组件
      </div>
    )
  }
})

父组件内容:

import CesiumMap from '@/components/Map';

interface Props {};

const MainPage = defineComponent<Props>((props, { slots, emit, attrs }) => {
  const cesiumRef = ref<typeof CesiumMap | null>(null);
  /**
   * 点击数据检索输入框右边框选查询按钮
   */
  const handleKuangxuan = (type: string, open: boolean) => {
    console.log('cesiumRef:::', cesiumRef)
  };

  return () => {
    return (
      <div class="tsd-mainpage">
        <CesiumMap ref={cesiumRef} />
        <DataQuery
          onKuangxuan={handleKuangxuan}
        />
      </div>
    )
  }
});

cesiumRef的内容如下:vue3项目,通过defineComponent创建的组件,在父组件中想通过ref拿到该组件内部的方法,从控制台看,ref对象中没有相关属性,这是为什么,正确要怎么做?

补充:通过这样来写,是正常能访问到的,但我不太想这么写:

export default defineComponent({
  name: 'CesiumMap',
  setup(props, { emit }) {
    const user = ref('测试')
    const exportFile = () => {
      emit('exportShpFile');
    };
    return {
      user,
      exportFile
    }
  },
  render() {
    return (
      <div>
        { this.user }
      </div>
    );
  }
});
回复
1个回答
avatar
test
2024-06-28

没试过,但是通过看defineComponent的文档,你可以试试看,能否在defineComponent的第二个参数对象中,添加expose属性。

如果不行的话,也可以在onMounted中将要暴露给父组件的方法/属性,emit给父组件

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容