一、 父级向子集传递参数
父组件关键代码
<template>
<Child :child="msg"></Child>
</template>
子组件关键代码
export default {
name: 'child',
props: {
child: String
}
};
props 负责接收父组件传递的参数,父组件中的:child
是传递到子组件props的参数
二、 子组件调用父组件
子组件关键代码
$emit
子组件中某函数内发送事件:
this.$emit('toparentevent', 'data');
toparentevent是传递到父组件的方法名,data是传递的参数,至于父组件怎么接收 往下看
父组件关键代码
<template>
<Child :child="msg" @toparentevent="todo()"></Child>
</template>
toparentevent 为子组件自定义发送事件名称,父组件中@toparentevent为监听事件,todo为父组件处理方法。
三、父组件直接获取子组件属性或方法
给要调用的子组件起个名字。将名字设置为子组件 ref 属性的值。
<!-- 子组件。 ref的值是组件引用的名称 -->
<template>
<Child :child="msg" @toparentevent="todo()" ref="Name"></Child>
</template>
父组件中通过 $refs.组件名 来获得子组件,也就可以调用子组件的属性和方法了。
var child = this.$refs.Name
child.属性
child.方法()