Vue從零開(kāi)始總結(jié)26
父?jìng)髯訉?shí)現(xiàn)了,那么子傳父呢?很簡(jiǎn)單,同樣的道理
首先我們要縷清一個(gè)邏輯,item(子組件里面的數(shù)據(jù))以參數(shù)的形式,先通過(guò)子組件內(nèi)的函數(shù)傳遞給自身,再通過(guò)這個(gè)函數(shù)將這個(gè)參數(shù)以一個(gè)事件的方式發(fā)送出去,在子組件標(biāo)簽行內(nèi)書寫這個(gè)事件,這個(gè)事件后面跟著父組件負(fù)責(zé)接受的函數(shù),它可以省略參數(shù),默認(rèn)傳遞item,而在瀏覽器內(nèi)默認(rèn)傳遞的事event事件,注意區(qū)分!
<template id="son">
?<div>
? <button v-for="item in detail" @click="btn_click(item)">{{item.name}}</button>
?</div>
</template>
item傳遞給自身函數(shù)btn_click
子組件:
components:{
?cpn: {
? ?template: '#son',
? ?data(){
? ? ?return {
? ? ? ?detail:[
? ? ? ? ? ?{id:1,name:'番劇'},
? ? ? ? ? ?{id:2,name:'音樂(lè)'},
? ? ? ? ? ?{id:3,name:'舞蹈'},
? ? ? ? ? ?{id:4,name:'推薦'}
? ? ? ?]
? ? ?}
? ?},
methods:{
//接受自身傳遞過(guò)來(lái)的item,以x的形式表達(dá)
?btn_click(x){
? ?this.$emit('item_click',x); //將x和自定義事件發(fā)送給父組件
?}
}
}
子組件標(biāo)簽行內(nèi):
<div id="app">
<cpn @item_click="clickMessage"></cpn>//將自定義事件傳遞給父組件的clickMessage函數(shù)
省略參數(shù),默認(rèn)傳遞item
</div>
父組件:
methods:{
?clickMessage(y){
? ?console.log('itemClick',y);//接收到子組件傳遞過(guò)來(lái)的x
?}
}
效果如下:
