uni-app开发Vue父组件调用子组件的属性和方法

uni-app开发Vue父组件调用子组件的属性和方法

先定义一个简单的子组件 main/index.vue

<template>
    <view>        
    </view>
</template>
<script>
    export default {
        data(){
            return {                
            }
        },
        onLoad(){            
        },
        methods:{
            childMethod() {
                console.log('childMethod do...')
            }
        }
    }
</script>
<style>
</style>

我们在子组件中定义了一个childMethod方法 ,怎么使用它呢?

首先父组件 import mainindex from ‘@/pages/main/index/index.vue’ 子组件 #这是自定义的子组件#

<template>
    <view class="content">
        <mian-index ref="mainindex"></mian-index>
        <view @tap="dataAction">button</view>
    </view>
</template>
<script>
    import mainindex from '@/pages/main/index/index.vue'
    export default {
        data() {
            return {
            };
        },
        components:{
            'mian-index':mainindex
        },
        onLoad(e) {
        },
        methods:{
            dataAction:function(){
                this.$refs.mainindex.childMethod();//这句是引用子组件方法重点
            }
        }
    }
</script>
<style scoped>
.content{
    width:100%;
    box-sizing: border-box;
}
</style>

总结:$refs和生命周期有关【必须页面渲染完毕之后 才能正常访问其内部的属性】

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x