首页 > 技术文章 > uniapp小程序父组件与子组件之间调用方法

pdxbb 2020-05-05 14:51 原文

前言:最近公司安排做一个仿微信聊天的小程序,先实现聊天的基本功能,在项目过程中遇到一些小的知识点,在这里做下笔记;

由于之前没有用过VUE,也没有做过小程序,在看了VUE官网和uniapp官网后,开始边学边做。

一,子组件调用父组件的方法

子组件  IMMsg

<template>
    <view>
        <button @tap="showData(items)">获取数据</button>
    </view>
</template>

<script>
    export default {
        name: 'IMMsg',
        props:{
                
        },
        data() {
            return {
                items:[
                    {
                        'key':'content',
                        'label':'内容'
                    }
                ]
            };
        },
        methods:{
            showData: function(data) {
                this.$emit("msg", data);

            }
        }
    }
</script>

<style>

</style>

 

父组件中调用子组件的showData方法

父组件  chat.vue

<template>
    <view>
        <IMsg @msg="showData"></IMsg>
    </view>
</template>

<script>
// 引入 IM 组件
import IMsg from '../../components/IMsg.vue';
export default {
    data() {
        return {
            datas:''
        };
    },
    methods: {
        showData: function(dd) {
            this.datas=dd;
            console.log(this.datas);
        }
    },
    components:{
        IMsg
    }
};
</script>

<style></style>

输出结果:

 二,父组件调用子组件的方法

子组件  IMMsg

<template>
    <view>
    </view>
</template>

<script>
    export default {
        name: 'IMMsg',
        props:{
                
        },
        data() {
            return {
                items:[
                    {
                        'key':'content',
                        'label':'内容'
                    }
                ]
            };
        },
        methods:{
            showData: function(data) {
                console.log(this.items);

            }
        }
    }
</script>

<style>
</style>

父组件  chat.vue

<template>
    <view>
        <IMsg ref="IMsg"></IMsg>
        <button @tap="getData">调用子组件的方法</button>
    </view>
</template>

<script>
// 引入 IM 组件
import IMsg from '../../components/IMsg.vue';
export default {
    data() {
        return {
            datas:''
        };
    },
    methods: {
        getData: function() {
            this.$refs.IMsg.showData();
        }
    },
    components:{
        IMsg
    }
};
</script>

<style></style>

注:父组件可以通过$refs拿到子组件的对象

  然后直接调用子组件的 methods里的方法和data里的数据

打印结果:

 

推荐阅读