【前端--Vue】组件之间的多种通信方式,一文彻底搞懂组件通信!
在Vue.js中,组件间的通信方式主要有以下几种:
- 父子组件通信:props / $emit
- 子父组件通信:$emit / v-on
- 兄弟组件通信:EventBus / Vuex
- 跨级组件通信:EventBus / Vuex / provide / inject
- 任意组件通信:EventBus / Vuex
下面是每种方式的示例代码:
- 父子组件通信:
父组件:
<template>
<ChildComponent :parentData="parentData" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: '父组件数据'
};
}
};
</script>
子组件:
<template>
<div>{{ parentData }}</div>
</template>
<script>
export default {
props: ['parentData']
};
</script>
- 子父组件通信:
子组件:
<template>
<button @click="sendToParent">发送给父组件</button>
</template>
<script>
export default {
methods: {
sendToParent() {
this.$emit('fromChild', '子组件数据');
}
}
};
</script>
父组件:
<template>
<ChildComponent @fromChild="receiveFromChild" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
receiveFromChild(data) {
console.log(data); // 输出:子组件数据
}
}
};
</script>
- 兄弟组件通信:使用EventBus
EventBus.js:
import Vue from 'vue';
export const EventBus = new Vue();
兄弟组件A:
<template>
<button @click="sendToSibling">发送给兄弟组件B</button>
</template>
<script>
import { EventBus } from './EventBus.js';
export default {
methods: {
sendToSibling() {
EventBus.$emit('fromSiblingA', '数据从A发出');
}
}
};
</script>
兄弟组件B:
<template>
<div>{{ dataFromSiblingA }}</div>
</template>
<script>
import { EventBus } from './EventBus.js';
export default {
data() {
return {
dataFromSiblingA: ''
};
},
created() {
EventBus.$on('fromSiblingA', (data) => {
this.dataFromSiblingA = data;
});
}
};
</script>
- 跨级组件通信:使用EventBus或Vuex
这里以EventBus为例:
EventBus.js:
import Vue from 'vue';
export const EventBus = new Vue();
子组件:
<template>
<button @click="sendToParent">发送给父组件</button>
</template>
<script>
import { EventBus } from './EventBus.js';
export default {
methods: {
sendToParent() {
EventBus.$emit('fromChild', '数据从子组件发出');
}
}
};
</script>
父组件:
<template>
<div>{{ dataFromChild }}</div>
</template>
<script>
import { EventBus } from
评论已关闭