###### tags: `vue`, `front-end`, `javascript` # 【自學筆記】從0開始學Vue - Day7 關於 Vue.component(prop、emit) 關於Vue,一直以來都多少有接觸,但都沒有好好的理解過它 就來做個一系列的學習筆記,紀錄學習Vue的過程吧 基本上就以到處拜讀前輩大神的文章,並整理成我理解的文字的方式進行 --- 上一篇有提到Vue應用主要是以多個元件搭建起來的,而每個Component中的data都是獨立的,若需資料傳遞,主要會使用`props`或`emit`兩種方式 **Props:由外向內傳入,特性為資料一更新,則傳入 data ,隨即更新頁面。** **Emit:由內向外傳出,特性為事件觸發才更新資料,屬於事件類型。** ### props介紹與使用 * 父層元件將內容傳進子層元件就需要用到`props`這個屬性。 * 陣列型態 * 寫法:``:props-in="msg"``,其中,`props-in`是自定義屬性、`msg`是傳入的內容 :::danger `HTML`屬性需要使用`kebab-case`,全小寫並使用分隔符號`-`來設定 ::: 例如: ```htmlembedded= <div id="app"> <my-component :parent-msg="parent_msg"></my-component> </div> ``` ```javascript= Vue.component('my-component', { props: ["parentMsg"], template: ` <div class="component"> <div> 來自父層: {{ parentMsg }} </div> <div> 元件本身data的msg: {{ msg }} </div> </div> `, data: function () { return { msg: '子層的訊息' } } }); new Vue({ el: '#app', data: { parent_msg: '父層的訊息' } }); ``` 資料傳遞過程圖解: ![](https://i.imgur.com/aeNCF5j.png) ### emit介紹 * 子層元件將內容傳進父層元件就需要用到`emit`這個屬性。 * 寫法: 1. 元件`html template`中綁定觸發事件`updateText` 2. 子層透過`$emit`觸發外層`selfUpdate`事件 3. 元件`html`前面是子層事件`update`,後面是父層事件`selfUpdate` ```htmlembedded= <div id="app"> <div>Parent: {{ message }}</div> <div>Child:<my-component :parent-message="message" @update="selfUpdate"></my-component></div> </div> ``` ```javascript= Vue.component('my-component', { template: ` <div style="display:inline-block"> <input v-model="message"> <button @click="updateText">Update</button> </div>`, props: { parentMessage: String }, //字串型別 data() { return { message: this.parentMessage } }, methods: { updateText() { this.$emit('update', this.message); //this.message是子層的 } } }); new Vue({ el: '#app2', data: { message: 'hello' }, methods: { selfUpdate(val) { this.message = val; } } }); ``` 資料傳遞過程圖解: ![](https://i.imgur.com/i9x9olS.png) --- *參考資料: https://reurl.cc/q5jm8g* *新手工程師的筆記,純粹記錄學了些啥東西 如果有前輩高人讀了我的文,文中有任何錯誤再麻煩指教指教*