温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中怎么实现父子组件间通信

发布时间:2021-07-21 14:32:49 来源:亿速云 阅读:138 作者:Leah 栏目:web开发

这篇文章将为大家详细讲解有关vue中怎么实现父子组件间通信,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

组件间通信($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>
          <h2>这是父组件</h2>
          <button @click = "getSonName">获取子组件数据</button>
          <span>{{mySonName}}</span>
          <hr>
          <xiaohua ref="mySon"></xiaohua>
        </div>
      `
    })
//  创建子组件
    Vue.component("xiaohua",{
      data:function(){
        return{
          name:"小花"
        }
      },
      template:`
          <h2>这是子组件</h2>
      `
    })
    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>
          <h2>这是父组件</h2>
          <hr>
          <xiaohua></xiaohua>
        </div>
      `
    })
    //创建子组件
    Vue.component("xiaohua",{
      data:function(){
        return{
          msg:""
        }
      },
      template:`
        <div>
            <h2>这是子组件</h2>
            <p>{{msg}}</p>
        </div>
      `,
      created:function(){
        //在子组件创建完成时获取父组件的数据
        //保存在msg中在p标签中显示
          this.msg = this.$parent.myName;
      }
    })
    new Vue({
      el:"#container",
      data:{
        msg:"Hello VueJs"
      }
    })
  </script>
 </body>
</html>

关于vue中怎么实现父子组件间通信就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI