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() // 我是父组件中的方法
}
Logo

前往低代码交流专区

更多推荐