目录
摘要:
在 Vue.js 2 中,
父组件向子组件传递数据通常通过属性传递的方式实现,
而子组件向父组件传递数据则通常使用自定义事件的方式。
子组件给父组件传值
$emit 触发事件:
- 子组件通过
$emit
方法触发一个事件,并且可以传递参数。 - 父组件可以通过监听子组件上
$emit
触发的事件来接收数据。
子组件传值
<template>
<button @click="sendToParent">Send</button>
</template>
<script>
export default {
methods: {
// 点击触发给父组件传值;
sendToParent() {
// 使用this.$emit('键','值') 传值;
this.$emit('custom-event', 'Hello from Child');
}
}
}
</script>
父组件接收
<child-component @custom-event="handleMessageFromChild"></child-component>
<script>
export default {
methods: {
// 使用v-on即简写@ 加 子组件传递的键值接收,可以将接收的值保存在本实列的data()中
handleMessageFromChild(message) {
console.log(message);
}
}
}
</script>
父组件给子组件传值
props:
- 在子组件中声明接受哪些属性(props)。
- 在父组件中,通过
<子组件名 :propName="value" />
的方式将数据绑定到子组件的属性上。
父组件传值
<template>
<div>
<child-component :myMessage="'Hello from Parent'"
ref="childInstance"> <!-- 给子组件添加 ref 属性 -->
</child-component>
<!-- 调用子组件的方法 -->
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
// 通过 ref 访问子组件实例并调用其方法
this.$refs.childInstance.childMethod();
}
}
};
</script>
子组件接收
<template>
<div>{{ myMessage }}</div>
</template>
<script>
export default {
props: ['myMessage'],
// 从子组件获取父组件的实例:this.$parent
// 可以解构,如:let {tableData} = this.$parent;
}
</script>
总结要点
①Vue.js 中推荐使用 props 进行父组件向子组件的数据传递,
并使用自定义事件($emit)进行子组件向父组件的数据传递。
②此外在子组件中可以使用 this.$parent获取父组件的实例,
在父组件中可以给子组件添加ref属性,通过 ref 访问子组件实例并调用其方法。