<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>componentParentChildCommunication</title>
    <script src="js/vue.js"></script>
  </head>


  <template ></child>
    </div>
  </template>

  <template >
    <div>I am child component:{{msg}}</div>
  </template>
  <body>


  <script>
    let child={
      template:'#childComp',
      data(){
        return {
          msg:'child Data'
        }
      },
      mounted(){
      /*this.$emit('自定义事件名',数据);*/
        this.$emit('child',this.msg);
      }
    };

    let parent={
      template:'#parentComp',
      data(){
        return {
          msg:'parent Data',
          msg2:''
        }
      },
      components:{
        child
      },
      methods:{
        parentFn(data){
          this.msg2=data;
        }
      }
    };


    window.onload=function(){
      new Vue({
        el:'#app',
        components:{
          parent
        }
      });
    }
    /*父元素向子元素通信关键总结:
      1:在嵌套的子元素(使用时)上:<child @自定义事件名="父方法"></child>;
      2:子元素在加载完成的钩子函数(mounted)上加一个方法:this.$emit('自定义事件名',数据);
      3:父元素上的方法:父方法名(data){...}
    */
  </script>


  <div >
    <parent></parent>
  </div>
  </body>
</html>

相关文章:

  • 2022-12-23
  • 2021-11-08
  • 2021-08-07
  • 2021-09-28
  • 2022-02-02
  • 2021-11-14
  • 2022-12-23
  • 2021-08-31
猜你喜欢
  • 2022-12-23
  • 2021-05-08
  • 2021-09-27
  • 2022-03-08
  • 2022-12-23
  • 2021-10-24
  • 2021-09-27
相关资源
相似解决方案