Vue父子組件交互

本文標識 : V00013

本文編輯 : Jack 風 編程工具 : Vscode 閱讀時長 : 3分鐘

父組件向子組件傳值

1. 組件實例定義方式,注意:一定要使用`props`屬性來定義父組件傳遞過來的數據

<script>      // 創建 Vue 實例,得到 ViewModel      var vm = new Vue({        el: '#app',        data: {          msg: '這是父組件中的消息'        },        components: {          son: {            template: '<h1>這是子組件 --- {{finfo}}</h1>',            props: ['finfo']          }        }      });    </script>

2. 使用`v-bind`或簡化指令,將數據傳遞到子組件中:

<div id="app">      <son :finfo="msg"></son>    </div>

子組件向父組件傳值

  1. 原理: 父組件將方法的引用,傳遞到子組件內部,子組件在內部調用父組件傳遞過來的方法,同時把要發送給父組件的數據,在調用方法的時候當作參數傳遞進去;
  2. 父解析 父組件將方法的引用傳遞給子組件,其中,getMsg是父組件中methods中定義的方法名稱,func是子組件調用傳遞過來方法時候的方法名稱<son @func="getMsg"></son>
  3. 子解析

子組件內部通過this.$emit('方法名', 要傳遞的數據)方式,來調用父組件中的方法,同時把數據傳遞給父組件使用

<div id="app">      <!-- 引用父組件 -->      <son @func="getMsg"></son>    <!-- 感謝關注公號 A2Data -->        <!-- 組件模板定義 -->      <script type="x-template" id="son">        <div>          <input type="button" value="向父組件傳值" @click="sendMsg" />        </div>      </script>    </div>        <script>      // 子組件的定義方式      Vue.component('son', {        template: '#son', // 組件模板Id        methods: {          sendMsg() { // 按鈕的點擊事件            this.$emit('func', 'OK'); // 調用父組件傳遞過來的方法,同時把數據傳遞出去          }        }      });          // 創建 Vue 實例,得到 ViewModel      var vm = new Vue({        el: '#app',        data: {},        methods: {          getMsg(val){ // 子組件中,通過 this.$emit() 實際調用的方法,在此進行定義            alert(val);          }        }      });    </script>