vue.js 中兄弟組件方法調用文章來源:http://www.zghlxwxcb.cn/news/detail-635817.html
場景:父組件中同時引入兩個子組件(A和B),此時B組件點擊按鈕需要調用A組件里面的方法
方案1:vue的事件總線
方案2:自定義事件($emit)
最終方案:方案2文章來源地址http://www.zghlxwxcb.cn/news/detail-635817.html
父組件
- 具體操作
- B組件上添加一個自定義的事件,這個是B組件傳遞給父組件的 @getList=getlist
- A組件上添加 ref 屬性 ref=‘componenta’
- 添加 getList方法
<template>
<div class="container">
<component-a ref="componenta"/>
<component-b @getList="getList"/>
</div>
</template>
<script>
export default {
methods:{
getList() {
// 這是關鍵
this.$refs.componenta.testA();
}
}
}
</script>
B組件
- 具體操作
- 使用$emit給父組件發(fā)送事件
<template>
<div class="container">
<button @click="test"> 調用A組件里面的方法 </button>
</div>
</template>
<script>
export default {
methods:{
test() {
this.$emit("getList");
}
}
}
</script>
A組件
<template>
<div class="container">
AAAAAAAA
</div>
</template>
<script>
export default {
methods:{
testA() {
console.log("AAAAAAA")
}
}
}
</script>
到了這里,關于vue.js兄弟組件方法調用b組件調用a組件方法的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!