Home > Web Front-end > JS Tutorial > Communication of Vue.js components from the parent component to the child parent component (code)

Communication of Vue.js components from the parent component to the child parent component (code)

高洛峰
Release: 2017-03-12 11:34:51
Original
1310 people have browsed it

This article Vue.jsCommunication of the component from the parent component to the child parent component (code)

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

  <template id="parentComp">
    <p>
      I am parent component:{{msg}},The Data from child:{{msg2}}
      <hr>
      <!-- <child @自定义事件名="父方法"></child> -->
      <child @child="parentFn"></child> 
    </p>
  </template>
  <template id="childComp">
    <p>I am child component:{{msg}}</p>
  </template>
  <body>

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

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

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

  <p id="app">
    <parent></parent>
  </p>
  </body>
</html>
Copy after login

The above is the detailed content of Communication of Vue.js components from the parent component to the child parent component (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template