纯vue实现父子组件
纯 Vue 实现父子组件
在 Vue 中,父子组件的通信和实现主要通过 props 和 events 完成。以下是实现父子组件的核心方法:
父组件向子组件传递数据
父组件通过 props 向子组件传递数据。子组件需要在 props 选项中声明接收的属性。
父组件代码示例:
<template>
<div>
<child-component :message="parentMessage" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent'
};
}
};
</script>
子组件代码示例:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
};
</script>
子组件向父组件发送事件
子组件通过 $emit 触发事件,父组件通过 v-on 监听子组件的事件。

子组件代码示例:
<template>
<button @click="notifyParent">Click me</button>
</template>
<script>
export default {
methods: {
notifyParent() {
this.$emit('child-event', 'Data from child');
}
}
};
</script>
父组件代码示例:
<template>
<div>
<child-component @child-event="handleChildEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildEvent(data) {
console.log(data); // 输出: 'Data from child'
}
}
};
</script>
使用插槽(Slots)传递内容
父组件可以通过插槽向子组件传递模板内容。

子组件代码示例:
<template>
<div>
<slot></slot>
</div>
</template>
父组件代码示例:
<template>
<child-component>
<p>This content is passed from parent</p>
</child-component>
</template>
动态组件
父组件可以通过动态组件的方式加载不同的子组件。
父组件代码示例:
<template>
<div>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
currentComponent: 'ChildComponent'
};
},
components: {
ChildComponent
}
};
</script>
以上方法涵盖了 Vue 中父子组件通信的主要方式,包括 props、events、slots 和动态组件。根据实际需求选择合适的方式即可。






