# Vue學習#14 元件資料傳遞 ###### tags: `Vue 直播班 - 2022 春季班` `Vue` ## props - 由外部元件傳入資料 由於每個元件的 data 都是獨立的(即使 data 裡面的變數名稱都相同) , props 的主要功能就是可以將不同的元件 data 傳到自己的元件來使用 使用口訣: 1. 元件內宣告 props:['自訂名稱'] 2. 元件標籤使用 v-bind:props名稱="外層元件data" (前內後外) 3. template 的標籤使用 v-model 綁定 props 接到外層資料的名稱 4. 單向數據流,不能直接修改用 props 綁定的 data ### 如果修改 props 綁定的 data 會發生什麼錯誤 ![](https://i.imgur.com/WsfxeDj.png) props 的資料只能讀,並不能進行修改 ### 單向數據流的解決辦法 -- 假設你想要修改 props 抓到的 data 1. 在元件內新增一個 data 變數 2. 在元件初始化 (mounted) 的時候 將新增的 data 變數賦予 props 所綁定的外層元件值 3. template v-model的值改指向自己元件的 data 變數 ```=Vue data () { return { tempdataInModal: this.tempData// 用一個變數將props抓到的外層資料儲存下來,避免單向數據流(不能修改父元件資料)的錯誤 }; }, props: ['tempData'] ``` #### [props範例](https://codepen.io/binlandz123/pen/OJOzxNe?editors=1011) #### [props 解決單向數據流範例](https://codepen.io/binlandz123/pen/OJOQVxe) ### props 進行型別驗證 除了傳遞資料以外,props 也可以進行傳入資料的型別驗證 1. 將 props 由陣列 [] 轉成 物件 {} 2. props 裡面的物件 key 就是 props 的名稱 3. 可使用的參數 required 、 default 、 資料型別 等等 4. 驗證只會在開發者工具給出警告,並不會影響運作 #### [props資料驗證範例](https://codepen.io/binlandz123/pen/JjMpKbX) ## emit - 由內部向外發送事件 用一張圖來講解 emit 的運作 ![](https://i.imgur.com/xp1C8cB.png) 圖例講解: 1. 在子元件 button-counter 有一個 function 叫做 click , 宣告了一個 emit 並把自訂名稱叫做 emit-num 2. 而在元件標籤內 (<button-counter></button-counter>) , 用 `v-on` 讓 emit 跟 其他元件的函式做綁定 `v-on:emit-num="addNum"` 3. 在 button-counter 這個元件下的 template 的標籤用 v-on 進行綁定事件,但是這次綁定的是自己的事件哦 `@click="click"` 在 click 函式裡面的 emit 將 click 這個函式往外傳,而標籤用 v-on 綁定的 emit 再去呼叫根元件的 addNum 這個函式 使用口訣: 1. 元件內的一個函式宣告 emit , this.$emit('自訂名稱','參數') , 參數為要綁定的函式是否有參數來決定 2. 到元件的標籤內使用 v-on 讓 emit 綁定外面元件的函式 , v-on:emit名稱="外層元件函式" (前內後外) 3. template 的標籤使用 v-on 綁定自己元件下的函式(在這裡指的是有宣告 emit 的那個函式),或是直接在標籤內宣告emit #### [emit範例](https://codepen.io/binlandz123/pen/abVqOrK?editors=1010) ## props 跟 emit 不適合跨兩層以上的元件間傳遞資料