Vue2.0入門系列——父子組件間通訊

一、子組件更新,父組件不變vue

點擊「按鈕」按鈕,子組件數據被修改,父組件數據不變this

 =========>>>>>> spa

 

項目源代碼,component

<head>blog

    <meta charset="UTF-8">ip

    <title>v2.0父子組件通訊</title>input

    <script src="./vue.js"></script>it

       <script>io

         window.onload=function(){function

            new Vue({

                   el: '#box',

                      data: {

                         aa: '我是父組件中的數據'

                      },

                      components: {

                         'child-com': {

                               props: ['msg'],  //接收父組件傳遞過來的信息

                               template: '#child',

                               methods:{

                               change(){

                                  this.msg='被修改'

                                  }

                               }

                            }

                      }

               });

         };

       </script>

       <!--子組件修改不能改變父組件的修改-->

</head>

<body>

    <template id="child">

         <div>

          <h3>我是子組件</h3>

          <input type="button" value="按鈕" @click="change">

          <strong>{{msg}}</strong>

         </div>

       </template>

       <div id="box">

         父級: -> {{ aa }}

         <child-com :msg="aa"></child-com>

       </div>

</body>

 

二、子組件更新,父組件隨之更新

點擊「按鈕」按鈕,父子組件均數據被修改,

<head>

    <meta charset="UTF-8">

    <title>v2.0父子組件通訊</title>

    <script src="./vue.js"></script>

       <script>

         window.onload=function(){

            new Vue({

                   el: '#box',

                      data: {

                         giveData:{

                              aa: '我是父組件中的數據'

                            }

                      },

                      components: {

                         'child-com': {

                               props: ['msg'],  //接收主組件傳遞過來的信息

                               template: '#child',

                               methods:{

                               change(){

                                    //this.msg='被修改'

                                          this.msg.aa='被修改'

                                  }

                               }

                            }

                      }

               });

         };

       </script>

       <!--子組件修改不能改變父組件的修改-->

</head>

<body>

    <template id="child">

         <div>

          <h3>我是子組件</h3>

          <input type="button" value="按鈕" @click="change">

          <strong>{{msg.aa}}</strong>

         </div>

       </template>

       <div id="box">

         父級: -> {{ giveData.aa }}

         <child-com :msg="giveData"></child-com>

       </div>

</body>

相關文章
相關標籤/搜索