父子组件间数据通信(2)
前言
在 https://blog.csdn.net/lw18751836671/article/details/123571072
中写了父子组件通讯的第一种方式,还有一种方式,使用 $parent 和 $refs 来完成父子间通讯。
父子间传递数据
主要依靠 this.$parent.method/data 和 this.$refs.childName.method/data
子组件
定义一个全局组件,如下,组件名称是my-son,里面有两个方法,sonFatherSay中可以通过 this.$parent 访问父组件的方法和数据。
<script>
Vue.component('my-son',{
template:`<div>
<button @click="sonSay">sonSay</button>
<button @click="sonFatherSay">fatherSay</button>
</div>`,
data(){
return {
sonData:{
name:"son"
}
}
},
methods:{
sonSay(){
console.info("son sonData:"+this.sonData.name);
},
sonFatherSay(){
this.$parent.fatherSay();
console.log("son fatherData:"+this.$parent.fatherData.name);
}
},
components:{
}
});
</script>
父组件
父组件中使用子组件,同时在使用子组件时加上 ref 这个属性,就可以访问子组件的数据和方法。
访问子组件的方法和数据需要使用 this.$refs.childName
<div id="app">
son:<my-son ref="son"></my-son>
<div>father:
<button @click="fatherSay">fatherSay</button>
<button @click="fatherSonSay">sonSay</button>
</div>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
fatherData:{
name:"father"
}
},
methods:{
fatherSay(){
console.info("father fatherData:"+this.fatherData.name);
},
fatherSonSay(){
this.$refs.son.sonSay();
console.log("father sonSay:"+this.$refs.son.sonData.name);
}
}
});
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?