Vue $emit $refs子父組件間方法的調(diào)用實(shí)例
1、$emit
子組件調(diào)用父組件的方法并傳遞數(shù)據(jù)
注意:子組件標(biāo)簽中的時(shí)間也不區(qū)分大小寫要用“-”隔開
子組件:
<template>
<button @click="emitEvent">點(diǎn)擊我</button>
</template>
<script>
export default {
data() {
return {
msg: "我是子組件中的數(shù)據(jù)"
}
},
methods: {
emitEvent(){
this.$emit('my-event', this.msg)
//通過按鈕的點(diǎn)擊事件觸發(fā)方法,然后用$emit觸發(fā)一個(gè)my-event的自定義方法,傳遞this.msg數(shù)據(jù)。
}
}
}
</script>
父組件:
<template>
<div id="app">
<child-a @my-event="getMyEvent"></child-a>
<!--父組件中通過監(jiān)測(cè)my-event事件執(zhí)行一個(gè)方法,然后取到子組件中傳遞過來的值-->
</div>
</template>
<script>
import ChildA from './components/child.vue'
export default {
components: {
ChildA
},
methods: {
getMyEvent(msg){
console.log('接收的數(shù)據(jù)--------->'+msg)//接收的數(shù)據(jù)--------->我是子組件中的數(shù)據(jù)
}
}
}
</script>
2、$refs
父組件調(diào)用子組件的方法,可以傳遞數(shù)據(jù)
注意:子組件標(biāo)簽中的時(shí)間也不區(qū)分大小寫要用“-”隔開
父組件:
<template>
<div id="app">
<child-a ref="child"></child-a>
<!--用ref給子組件起個(gè)名字-->
<button @click="getMyEvent">點(diǎn)擊父組件</button>
</div>
</template>
<script>
import ChildA from './components/child.vue'
export default {
components: {
ChildA
},
data() {
return {
msg: "我是父組件中的數(shù)據(jù)"
}
},
methods: {
getMyEvent(){
this.$refs.child.emitEvent(this.msg);
//調(diào)用子組件的方法,child是上邊ref起的名字,emitEvent是子組件的方法。
}
}
}
</script>
子組件:
<template>
<button>點(diǎn)擊我</button>
</template>
<script>
export default {
methods: {
emitEvent(msg){
console.log('接收的數(shù)據(jù)--------->'+msg)//接收的數(shù)據(jù)--------->我是父組件中的數(shù)據(jù)
}
}
}
</script>
以上這篇Vue $emit $refs子父組件間方法的調(diào)用實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue2利用Bus.js如何實(shí)現(xiàn)非父子組件通信詳解
這篇文章主要給大家介紹了關(guān)于vue2利用Bus.js如何實(shí)現(xiàn)非父子組件通信的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08
Vue實(shí)現(xiàn)動(dòng)態(tài)圓環(huán)百分比進(jìn)度條
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)動(dòng)態(tài)圓環(huán)百分比進(jìn)度條,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Vue.js 單頁面多路由區(qū)域操作的實(shí)例詳解
這篇文章主要介紹了 Vue.js 單頁面多路由區(qū)域操作的實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-07-07
vue截圖轉(zhuǎn)base64轉(zhuǎn)文件File異步獲取方式
這篇文章主要介紹了vue截圖轉(zhuǎn)base64轉(zhuǎn)文件File異步獲取方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
移動(dòng)端滑動(dòng)切換組件封裝 vue-swiper-router實(shí)例詳解
這篇文章主要介紹了移動(dòng)端滑動(dòng)切換組件封裝 vue-swiper-router實(shí)例詳解,需要的朋友可以參考下2018-11-11
vue3中使用pinia(大菠蘿)狀態(tài)管理倉庫的項(xiàng)目實(shí)踐
本文主要介紹了vue3中使用pinia(大菠蘿)狀態(tài)管理倉庫,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

