vue组件父子间通信02

三、组件间通信($parent $refs)


父组件要想获取子组件的数据:
①在调用子组件的时候,指定ref属性
<child-component ref="mySon"></child-component>

②根据指定的引用的名字 找到子组件的实例对象
this.$refs.mySon

子组件要想获取父组件的数据:
①直接读取
this.$parent

:::通过this.$refs拿到子组件的数据

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>组件间通信-01</title>
    <script src="js/vue.js"></script>
 </head>
 <body>
  <div id="container">
        <p>{{msg}}</p>
        <dahua></dahua>
    </div>
    <script>
    //vue提供的ref
        Vue.component("dahua",{
            data:function(){
                return{
                    mySonName:""
                }
            },
            methods:{
            //通过$refs拿到指定的所引用的对应的组件的实例对象
                getSonName:function(){
                    this.mySonName = this.$refs.mySon.name;
                }
            },
            template:`
                <div>
                    <h1>这是父组件</h1>
                    <button @click = "getSonName">获取子组件数据</button>
                    <span>{{mySonName}}</span>
                    <hr>
                    <xiaohua ref="mySon"></xiaohua>
                </div>
            `
        })
//    创建子组件
        Vue.component("xiaohua",{
            data:function(){
                return{
                    name:"小花"
                }
            },
            template:`
                    <h1>这是子组件</h1>
            `
        })
        new Vue({
            el:"#container",
            data:{
                msg:"Hello VueJs"
            }
        })
    </script>
 </body>
</html>

子组件通过$parent获取父组件的数据

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>组件间通信-02</title>
    <script src="js/vue.js"></script>
 </head>
 <body>
  <div id="container">
        <p>{{msg}}</p>
        <dahua></dahua>
    </div>
    <script>
        //创建子组件
        Vue.component("dahua",{
            data:function(){
                return{
                    myName:"大花"
                }
            },
            template:`
                <div>
                    <h1>这是父组件</h1>
                    <hr>
                    <xiaohua></xiaohua>
                </div>
            `
        })
        //创建子组件
        Vue.component("xiaohua",{
            data:function(){
                return{
                    msg:""
                }
            },
            template:`
                <div>
                        <h1>这是子组件</h1>
                        <p>{{msg}}</p>
                </div>
            `,
            created:function(){
                //在子组件创建完成时获取父组件的数据
                //保存在msg中在p标签中显示
                    this.msg = this.$parent.myName;
            }
        })
        new Vue({
            el:"#container",
            data:{
                msg:"Hello VueJs"
            }
        })
    </script>
 </body>
</html>
原文地址:https://www.cnblogs.com/wangruifang/p/7771995.html