关于父子组件那点事
父组件通过prop向子组件传递数据,父组件调用子组件方法
父组件通过ref直接调用子组件的方法;
Html部分
<div><Button @click=
"handleClick"
>点击调用子组件方法</Button>
<Child :title="title" ref="child"></Child> </div>
Js部分
<script>
import Child form "Child.vue";//引入组件方法一
export
default
{
componentsL{//注册组件
Child
//或者
Child:()=>import("Child.vue")//引入组件方法二,不需要上面的
},
methods: {
handleClick() {
this
.$refs.child.sing();//方法一
this
.$refs.child.$emit(
"childmethod"
)
//方法二:子组件$on中的名字
},
},
}
</script>
子组件
<div>
<div>{{title}}</div>
</div>
js部分
<script>
export
default
{
props:{
title: {
type: String,
default: ‘’,
},
},
mounted() {
this
.$nextTick(
function
() {
this
.$on(
'childmethods'
,
function
() {
console.log(
'我是子组件方法'
);
});
});
},
methods: {
sing() {
console.log(
'我是子组件的方法'
);
},
},
};
</script>
子组件调用父组件方法
方法一:父组件把方法传入子组件中,子组件用props接收,再调用这个方法。
父组件代码:
<template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import { child } from 'components/child.vue'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
子组件代码
<template> <div> <button @click="childMethod()">点击</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { this.fatherMethod(); } } }; </script>
2、
方法二在子组件里用$emit
向父组件触发一个事件,父组件监听这个事件。
父组件
<template> <div> <child @fatherMethod="fatherMethod"></child> </div> </template> <script> import { child } from 'components/child.vue'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
子组件
<template> <div> <button @click="childMethod()">点击</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod'); } } }; </script>
方法三:在子组件中通过this.$parent.event来调用父组件的方法。
父组件
<template> <div> <child></child> </div> </template> <script> import { child } from 'components/child.vue'; export default { components: { child }, methods: { fatherMethod() { console.log('测试'); } } }; </script>
子组件
<template> <div> <button @click="childMethod()">点击</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?