講故事前先講代碼
父組件向子組件傳值
父組件數(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é),也不會打字,所以寫了封信,去了郵局。

老王用筆在紙上寫了好多內(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)于父組件的值,拿了出來。