一個故事講懂vue父子組件傳值
作者:李佳明同學
鏈接:https://www.jianshu.com/p/2272b6ca0f0c
一個故事講懂vue父子組件傳值
講故事前先講代碼
父組件向子組件傳值
父組件數據傳遞給子組件可以通過props屬性來實現
父組件:
<template> <div id="app"> <child-component
v-bind:dataOfChild="dataOfParent">
</child-component> </div></template><script> import childComponent from ‘./components/childComponent‘ export default { name: ‘App‘, data(){ return {
dataOfParent:‘1111111111‘ } }, components:{ childComponent }, }</script>
子組件:
<script>export default {
name: ‘childComponent‘,
//子組件通過props來接收數據: props:[‘dataOfChild‘], data () { return {dataOfChild:this.dataOfChild } } }</script>
父向子傳值總結:
v-bind:dataOfChild="dataOfParent"
(父組件)====>props:[‘dataOfChild‘](子組件)
子組件向父組件傳值
子組件:
<template> <div> <button @click="sendDataToParent">
向父組件傳值</button> </div></template><script> export default {name: ‘childComponent‘,
methods:{ sendDataToParent:function () { //$emit(even,value)even 是一個函數,
value 是傳給父組件的值 this.$emit(‘parentFunction‘,
‘helloworld‘) }, } }</script>
父組件:
<template> <div id="app"> <!--監聽子組件觸發的parentFunction事件,
然後調用customParentFunction方法--> <child-component v-on:parentFunction=
"customParentFunction">
</child-component> </div></template><script> import childComponent from ‘./components
/childComponent‘ export default { name: ‘App‘,
components:{ childComponent }, methods: { customParentFunction:function (data) { console.log(‘子組件傳過來的值‘,data) //helloworld } } }</script>
子向父傳值總結:
this.$emit(‘parentFunction‘,
‘helloworld‘)(子組件)====> v-on:parentFunction="
customParentFunction"(父組件)====> customParentFunction:function
(data) {}(父組件)
接下來是強化記憶階段:
情節一
話說,在遙遠的大山那邊,有一對父子,父親叫老王,兒子叫小明。父親由於歲數大了,平常就在家幹點農活,小明為了養家,外出打工。
有一天,小明想爸爸了,拿起手機給爸爸發短信,子組件主動向父組件傳值
,小明拿起手機,調用sendDataToParent方法
,在通訊錄找到了爸爸的手機號,this.$emit的第一個參數,函數名
,
然後拿起手機,摳了一堆字:爸爸我想你了,最近怎麽樣?this.$emit的第二個參數,
內容
,然後發送~,短信傳到了信號塔,child-component相當於基站,基站對所有短信進行監聽,正好,基站的列表裏有小明父親的名單,===》v-on:parentFunction
,然後,短信又由基站傳到了老王那邊,老王的手機鈴想了:蒼茫的天涯是我的愛 綿綿的青山腳下花正開~~~響鈴相當於調用customParentFunction方法,然後,值就傳過來了
。
情節二
但是呢,小明在外打工,有時工作比較忙,忘了給爸爸發短信,所以老王想兒子了,但老王比較保守,又沒大上過學,也不會打字,所以寫了封信,去了郵局。
老王用筆在紙上寫了好多內容,把紙 紙相當於dataOfParent,也就是數據
放進了信封信封相當於屬性,也就是v-bind:dataOfChild
裏,然後給了郵局相當於child-component,相當於一個中介
,快遞員進行派送,小明來到郵箱相當於props
,看到裏邊有封信相當於父組件的值
,拿了出來。
這是我第一次用情景故事的形式來寫文章,也是一次新的嘗試,如有不足,或者錯的地方,還請大家多多指點。
本文完~
一個故事講懂vue父子組件傳值