在 Vue.js 中,父组件包含子组件,通过 props 和 slots 进行通信。注册父组件,在模板中插入子组件占位符 (slot),并传递 props。父组件可传递数据给子组件,子组件可触发事件,父组件监听并处理。
Vue 父组件:使用指南
在 Vue.js 中,父组件是包含一个或多个子组件的组件。子组件通过 props 与父组件进行通信,而父组件则通过 slots 来控制子组件的呈现方式。
如何使用父组件
在 Vue template 中使用父组件,遵循以下步骤:
立即学习“前端免费学习笔记(深入)”;
示例
// ParentComponent.vue <template> <div> <slot></slot> <!-- 占位符,接收子组件内容 --> </div> </template>
// ChildComponent.vue <template> <h1>我是子组件</h1> </template>
// App.vue <template> <ParentComponent> <ChildComponent></ChildComponent> <!-- 插入子组件 --> </ParentComponent> </template>
传递 props
父组件可以通过 props 向子组件传递数据。在父组件中,使用 v-bind 绑定 props 到子组件:
// ParentComponent.vue <template> <ChildComponent :message="message"></ChildComponent> </template>
在子组件中,声明 props 并使用 :propName 语法访问父组件传递的值:
// ChildComponent.vue <script> export default { props: ['message'] } </script> <template> <h1>{{ message }}</h1> </template>
事件处理
子组件可以向父组件触发事件。在子组件中,使用 $emit 方法触发事件:
// ChildComponent.vue <script> export default { methods: { clickHandler() { this.$emit('child-click') // 触发 child-click 事件 } } } </script> <template> <button @click="clickHandler">点击我</button> </template>
在父组件中,使用 v-on 监听子组件触发的事件:
// ParentComponent.vue <template> <ChildComponent @child-click="handleChildClick"></ChildComponent> </template>
以上就是vue父组件怎么用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号