講故事前先講代碼
父組件向子組件傳值
父組件數據傳遞給子組件可以通過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">
<!--監(jiān)聽子組件觸發(fā)的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) {}(父組件)
接下來是強化記憶階段:
情節(jié)一
話說,在遙遠的大山那邊,有一對父子,父親叫老王,兒子叫小明。父親由于歲數大了,平常就在家干點農活,小明為了養(yǎng)家,外出打工。
有一天,小明想爸爸了,拿起手機給爸爸發(fā)短信,子組件主動向父組件傳值
,小明拿起手機,調用sendDataToParent方法
,在通訊錄找到了爸爸的手機號,this.$emit的第一個參數,函數名,
然后拿起手機,摳了一堆字:爸爸我想你了,最近怎么樣?this.$emit的第二個參數,內容
,然后發(fā)送~,短信傳到了信號塔,child-component相當于基站,基站對所有短信進行監(jiān)聽,正好,基站的列表里有小明父親的名單,===》v-on:parentFunction
,然后,短信又由基站傳到了老王那邊,老王的手機鈴想了:蒼茫的天涯是我的愛 綿綿的青山腳下花正開~~~響鈴相當于調用customParentFunction方法,然后,值就傳過來了
。
情節(jié)二
但是呢,小明在外打工,有時工作比較忙,忘了給爸爸發(fā)短信,所以老王想兒子了,但老王比較保守,又沒大上過學,也不會打字,所以寫了封信,去了郵局。
老王用筆在紙上寫了好多內容,把紙
紙相當于dataOfParent,也就是數據
放進了信封信封相當于屬性,也就是v-bind:dataOfChild
里,然后給了郵局相當于child-component,相當于一個中介
,快遞員進行派送,小明來到郵箱相當于props
,看到里邊有封信相當于父組件的值
,拿了出來。本文是作者第一次用情景故事的形式來寫博客,也是一次新的嘗試,如有不足,或者錯的地方,還請大家多多指點。