vue 父组件给子组件传递一个函数

vue 中父子组件通信的基本原理是:父组件通过props给子组件下发一个属性来传递数据,而子组件通过emit去向上触发父组件中的事件来达到相互通信的目的。当然还有其他的,这个暂不讨论。
而props的数据类型可以是:

props: {
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise // or any other constructor
}

在父组件中,我们在子组件中给他绑定一个属性,而这个属性是一个函数

<template>
    <section class="section-container">
    <my-component :handlerSomethFun="handleSomethFun"></my-component>
</section>
</template>
<script>
import myComponent from './myComponent'
    export default {
        name: 'myComponent'
        data() {
            return {}
        },
        methods: {
            handleSomethFun() {
                console.log('我是父组件中的方法')
            }
        }
    }
</script>

在子组件中我们接收父组件传递过来的这个属性

props: {
    handlerSomethFun: {
        type: Function, // 它的类型是一个函数Function
        default: () => {}
    }
}
// 然后我们就可以在子组件的某个时刻调用父组件传递过来的这个函数了,当然数据来自父组件
created() {
    this.handlerSomethFun() // 我是父组件中的方法
}

————————————————
版权声明:本文为CSDN博主「Eason_0316」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qyl_0316/article/details/117331486

posted @ 2023-02-03 17:44  黑白棋学弟  阅读(378)  评论(0编辑  收藏  举报