父組件給子組件傳值
一、
? ? ? 1.在子組件標簽中寫入父組件傳遞數據 向下傳遞prop
? ? ? 2.在子組件內聲明props選項接收父組件傳遞的數據 props:['','','']
父組件:
<Header :msg='msg' ></Header>
子組件:
props:['msg'],
二、
? ? ? provide inject
? ? ? 1.父組件使用provide提供傳遞數據或者方法
? ? ? 2.子組件使用inject注入傳遞的數據或者方法
父組件:
provide(){return {parent:this.parent,parentSend:this.parentSend,attr:this.attr}}
子組件:
inject:['parent','parentSend'],
三、
? ? ? 事件總線 $emit 和 $on vue實例調用方法?
? ? ? 1.新建event.js?
? ? ? ? import Vue from 'vue';
? ? ? ? export default new Vue();
? ? ? 2.在父組件中使用$emit發射自定義事件同時傳遞參數
? ? ? import Bus from './event.js'
? ? ? Bus.$emit('自定義事件名稱',傳遞數據)
? ? ? 3.在子組件內部使用$on監聽自定義事件同時接收參數
? ? ? Bus.$on('自定義事件名稱',(a,b)=>{
? ? ? })
父組件:
import Bus from './event'Bus.$emit('toHeader',this.pMsg,'hello world')
子組件:
import Bus from '../event'Bus.$on('toHeader',(a,b)=>{console.log(a,b);this.a = a;this.b = b;})
子組件給父組件傳值
1.發射自定義事件給父組件同時傳遞數據
? ? ? this.$emit('toParent',this.footer);
? ? ? 2.在父組件模板中(在子組件標簽上)聲明自定義事件?
? ? ? <Footer @toParent='事件處理程序'></Footer>
? ? ? 事件處理程序(接收子組件傳遞的數據){
? ? ? }
兄弟組件傳值
利用事件總線?
? ? 1.定義事件總線 新建xxx.js
? ? ? ? import Vue from 'vue';
? ? ? ? export default new Vue();
? ? 2.在一個兄弟組件中引入事件總線?
? ? ? import Bus from './event.js'
? ? ? 使用Bus.$emit('自定義事件名稱',傳遞的數據)
? ? 3.在另一個兄弟組件中引入事件總線
? ? ? import Bus from './event.js'
? ? ? 使用Bus.$on('emit發射自定義事件名稱',(a,b)=>{
? ? ? ??
? ? ? })監聽發射自定義事件 同時接收數據
? ??
祖先后代組件傳值/通信
provide inject