Vue父子組件傳值:故事講解

講故事前先講代碼
父組件向子組件傳值
父組件數(shù)據(jù)傳遞給子組件可以通過props屬性來實現(xiàn)

父組件:

<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來接收數(shù)據(jù): 
  props:['dataOfChild'], 
  data () { 
    return {
      dataOfChild:this.dataOfChild 
    }   
  }
}
</script>

父向子傳值總結(jié):

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 是一個函數(shù),value 是傳給父組件的值 
      this.$emit('parentFunction','helloworld') 
    }, 
  } 
}
</script>

父組件:

<template> 
<div id="app"> 
  <!--監(jiān)聽子組件觸發(fā)的parentFunction事件,然后調(diào)用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>

子向父傳值總結(jié):

this.$emit('parentFunction','helloworld')(子組件)====>
v-on:parentFunction="customParentFunction"(父組件)====>
customParentFunction:function(data) {}(父組件)

接下來是強(qiáng)化記憶階段:

情節(jié)一

話說,在遙遠(yuǎn)的大山那邊,有一對父子,父親叫老王,兒子叫小明。父親由于歲數(shù)大了,平常就在家干點農(nóng)活,小明為了養(yǎng)家,外出打工。

有一天,小明想爸爸了,拿起手機(jī)給爸爸發(fā)短信,子組件主動向父組件傳值,小明拿起手機(jī),調(diào)用sendDataToParent方法,在通訊錄找到了爸爸的手機(jī)號,this.$emit 的第一個參數(shù),函數(shù)名,然后拿起手機(jī),摳了一堆字:爸爸我想你了,最近怎么樣?this.$emit的第二個參數(shù), 內(nèi)容,然后發(fā)送~,短信傳到了信號塔,child-component相當(dāng)于基站,基站對所有短信進(jìn)行監(jiān)聽,正好,基站的列表里有小明父親的名單,===》v-on:parentFunction,然后,短信又由基站傳到了老王那邊,老王的手機(jī)鈴想了:蒼茫的天涯是我的愛 綿綿的青山腳下花正開~~~響鈴相當(dāng)于調(diào)用customParentFunction方法,然后,值就傳過來了。

情節(jié)二

但是呢,小明在外打工,有時工作比較忙,忘了給爸爸發(fā)短信,所以老王想兒子了,但老王比較保守,又沒大上過學(xué),也不會打字,所以寫了封信,去了郵局。

image.jpeg

老王用筆在紙上寫了好多內(nèi)容,把紙 紙相當(dāng)于dataOfParent,也就是數(shù)據(jù)放進(jìn)了信封信封相當(dāng)于屬性,也就是v-bind:dataOfChild里,然后給了郵局相當(dāng)于child-component,相當(dāng)于一個中介,快遞員進(jìn)行派送,小明來到郵箱相當(dāng)于props,看到里邊有封信相當(dāng)于父組件的值,拿了出來。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容