c***@163.com
c***@163.com
  • 发布:2025-07-14 17:19
  • 更新:2025-07-16 10:53
  • 阅读:77

uniappX 如何调用组件的方法

分类:uni-app x

uniapp 中可以使用 $refs.XXX.方法名称() 就可以
但是在UniappX 中完全无法使用 也看了官方文档

      this.dom=this.$refs['child'] as ComponentPublicInstance  
        this.dom?.$callMethod('getNum') as number

这样写也不可以 求大神们 指点下
需求就是 当前页面 使用 import child from './a.uvue' 调用a组件中的test()方法

2025-07-14 17:19 负责人:无 分享
已邀请:
DCloud_UNI_JBB

DCloud_UNI_JBB

你是运行在什么端的?代码怎么写的?

  • c***@163.com (作者)

    运行 安卓 我只是学习 写写demo

    2025-07-14 17:41

  • DCloud_UNI_JBB

    回复 c***@163.com: 发下你的代码,我看看是你写的有问题还是框架这边有问题

    2025-07-14 19:01

c***@163.com

c***@163.com (作者) - 90后30而已

官方语法 (this.$refs['组件ref属性值'] as ComponentPublicInstance)?.$callMethod('方法名', ...args)

<-- 父页面 ->  
<template>  
    <view>  
        <child ref="c1"></child>  
    </view>  
</template>  

<script lang="uts">  
    import child from "./child.uvue"  
    export default {  
        components:{child},  
        data() {  
            return {  
                title: 'Hello'  
            }  
        },  
        onLoad() {  
           (this.$refs['c1' ] as ComponentPublicInstance )?.$callMethod('test','1234')  
        },  
        methods: {  

        }  
    }  
</script>  

<style>  
    .logo {  
        height: 100px;  
        width: 100px;  
        margin: 100px auto 25px auto;  
    }  

    .title {  
        font-size: 18px;  
        color: #8f8f94;  
    text-align: center;  
    }  
</style>  

<-- 组件页面 ->  
<template>  
    <view>  
        1  
    </view>  
</template>  

<script lang="uts">  
    export default {  
        name:"child",  
        data() {  
            return {  

            }  
        },  
        methods: {  
            test(str : string){  
                console.log("调用组件:"+str);  
            }  
        }  
    }  
</script>  

<style>  

</style>
c***@163.com

c***@163.com (作者) - 90后30而已

DCloud_UNI_JBB

DCloud_UNI_JBB

if (this.$refs['c1'] != null) {  
                (this.$refs['child'] as ComponentPublicInstance).$callMethod('test', '1234')  
            }

这样写就不会有问题了

要回复问题请先登录注册