父子组件间数据通信(2)

前言

在 https://blog.csdn.net/lw18751836671/article/details/123571072
中写了父子组件通讯的第一种方式,还有一种方式,使用 $parent$refs 来完成父子间通讯。

父子间传递数据

主要依靠 this.$parent.method/datathis.$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>
posted @   伟衙内  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示