provide inject
template>
<h1>Food</h1>
<div @click="this.activeComp = 'food-about'" class="divBtn">About</div>
<div @click="this.activeComp = 'food-kinds'" class="divBtn">Kinds</div>
<div id="divComp">
<component :is="activeComp"></component>
</div>
</template>
<script>
export default {
data() {
return {
activeComp: 'food-about',
foods: [
{ name: 'Pizza', imgUrl: '/img_pizza.svg' },
{ name: 'Apple', imgUrl: '/img_apple.svg' },
{ name: 'Cake', imgUrl: '/img_cake.svg' },
{ name: 'Fish', imgUrl: '/img_fish.svg' },
{ name: 'Rice', imgUrl: '/img_rice.svg' }
]
}
},
provide() {
return {
foods: this.foods
}
}
}
</script>
INJECT
<template>
<h2>Different Kinds of Food</h2>
<p><mark>In this application, food data is provided in "App.vue", and injected in the "FoodKinds.vue" component so that it can be shown here:</mark></p>
<div v-for="x in foods">
<img :src="x.imgUrl">
<p class="pName">{{ x.name }}</p>
</div>
</template>
<script>
export default {
inject: ['foods']
}
</script>
<style scoped>
div {
margin: 10px;
padding: 10px;
display: inline-block;
width: 80px;
background-color: #28e49f47;
border-radius: 10px;
}
.pName {
text-align: center;
}
img {
width: 100%;
}
</style>
events bus
In Vue.js, an event bus is a pattern used for communication between components that are not directly related through parent-child relationships. It involves creating a central instance of Vue that can emit and listen to events. Here’s an example of implementing an event bus in Vue.js:
- Create the Event Bus:
- // EventBus.js import Vue from 'vue'; export const EventBus = new Vue();
- Usage in Components:
Let's say you have two components, ComponentA
and ComponentB
, and you want them to communicate via the event bus.
// ComponentA.vue <template> <button @click="emitEvent">Emit Event</button> </template> <script> import { EventBus } from './EventBus'; export default { methods: { emitEvent() { EventBus.$emit('custom-event', 'Hello from ComponentA!'); } } } </script>
In this example:
ComponentA
emits a custom event named'custom-event'
with a message when the button is clicked.ComponentB
listens for the'custom-event'
and updates itsmessage
data when the event is received.
- Usage in App.vue (or your main Vue instance):
- // App.vue <template> <div id="app"> <ComponentA /> <ComponentB /> </div> </template> <script> import ComponentA from './ComponentA.vue'; import ComponentB from './ComponentB.vue'; export default { components: { ComponentA, ComponentB } } </script>
Ensure that all components (ComponentA
, ComponentB
, and the event bus EventBus
) are imported and properly set up within your Vue application.
This setup allows ComponentA
and ComponentB
to communicate indirectly through the event bus. When ComponentA
emits the custom event, ComponentB
picks it up and reacts accordingly.
No comments:
Post a Comment