inject通信
<script>
//接收组件
export default {
provide() {
return {
grandparentMethod: this.grandparentMethod
};
},
methods: {
grandparentMethod(message) {
console.log('祖父组件收到:', message);
}
}
}
</script>
<script>
//发送组件
export default {
inject: ['grandparentMethod'],
methods: {
notifyGrandparent() {
this.grandparentMethod('来自子组件的消息');
}
}
}
</script>
事件总线(Event Bus)
// eventBus.js
import Vue from 'vue';
export const EventBus = new Vue();
// request.js
import { EventBus } from './eventBus';
export function fetchData() {
axios.get('/api/data')
.then(response => {
EventBus.$emit('dataFetched', response.data); // 触发事件
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
// App.vue
<script>
import { EventBus } from './eventBus';
export default {
created() {
EventBus.$on('dataFetched', (data) => {
// 处理数据
console.log(data);
});
}
}
</script>