龙岗做网站公司聊城seo
vue.js 中兄弟组件方法调用
场景:父组件中同时引入两个子组件(A和B),此时B组件点击按钮需要调用A组件里面的方法
方案1:vue的事件总线
方案2:自定义事件($emit)
最终方案:方案2
父组件
- 具体操作
- 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给父组件发送事件
<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>