首页  >  文章  >  web前端  >  Vue.js组件的通信之子组件向父组件的通信(代码)

Vue.js组件的通信之子组件向父组件的通信(代码)

高洛峰
高洛峰原创
2017-03-12 11:36:431244浏览

这篇文章介绍Vue.js组件的通信之子组件向父组件的通信(代码)

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

  <template id="parentComp">
    <p>
      I am parent component:{{msg}},The Data from child:{{msg1}},{{msg2}}
      <hr>
      <child :m1="msg1" :m2="msg2"></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;
        }
      },
      props:[&#39;m1&#39;,&#39;m2&#39;]
    };

    let parent={
      template:&#39;#parentComp&#39;,
      data(){
        return {
          mgs:&#39;parent Data&#39;,
          msg1:&#39;the first parent Data&#39;,
          msg2:&#39;the second parent Data&#39;
        }
      },
      components:{
        child
      },
    };

    window.onload=function(){ 
      new Vue({
        el:&#39;#app&#39;,
        components:{
          parent
        }
      });
    }

    /*子元素向父元素通信关键总结:
      1:子元素定义时props:[&#39;msg1&#39;,&#39;msg2&#39;,&#39;msg3&#39;,...],用来放置从父元素拿过来的数据
      2:在嵌套的子元素(使用时)上:<child  :msg1="父数据1" :msg2="父数据2" :msg3="父数据3"></child>;
    */
  </script>
    <p id="app">
      <parent></parent>
    </p>
  </body>
</html>


以上是Vue.js组件的通信之子组件向父组件的通信(代码)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn