This project demonstrates various techniques for passing data between components in Vue 3 using Vite. The main goal is to provide clear examples of the following data-sharing methods:
- Parent to Child
- Child to Parent
- Global State for Multiple Components
- Vue Composition API
inject/providerefemit- Handling props
The project consists of the following components:
App.vue: The global root component.ComponentA.vue: A child ofApp.ComponentAA.vue: A child ofComponentA.ComponentAB.vue: A sibling ofComponentAA, also a child ofComponentA.
App.vue
├── ComponentA.vue
│ ├── ComponentAA.vue
│ └── ComponentAB.vue
This is achieved using props. The parent component passes data to its child as a property.
Example in App.vue:
<script setup>
import ComponentA from './components/ComponentA.vue';
const messageToA = 'Hello from App!';
</script>
<template>
<ComponentA :message="messageToA" />
</template>In ComponentA.vue:
<script setup>
import { defineProps } from 'vue';
defineProps(['message']);
</script>
<template>
<p>{{ message }}</p>
</template>This is achieved using events and emit.
In ComponentAA.vue:
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['updateParent']);
function sendToParent() {
emit('updateParent', 'Data from ComponentAA');
}
</script>
<template>
<button @click="sendToParent">Send to Parent</button>
</template>In ComponentA.vue:
<script setup>
function handleUpdate(data) {
console.log('Received from ComponentAA:', data);
}
</script>
<template>
<ComponentAA @updateParent="handleUpdate" />
</template>This is achieved using provide and inject.
In App.vue:
<script setup>
import { provide, ref } from 'vue';
import ComponentA from './components/ComponentA.vue';
const globalMessage = ref('Shared Message');
provide('globalMessage', globalMessage);
</script>
<template>
<ComponentA />
</template>In ComponentA.vue:
<script setup>
import { inject } from 'vue';
import ComponentAA from './ComponentAA.vue';
import ComponentAB from './ComponentAB.vue';
const globalMessage = inject('globalMessage');
</script>
<template>
<p>Global Message: {{ globalMessage }}</p>
<ComponentAA />
<ComponentAB />
</template>-
Clone the repository:
git clone [email protected]:guduchango/vue3-components-data-share.git cd vue3-components-data-share
-
Install dependencies:
npm install
-
Run the project:
npm run dev
-
Open in your browser:
http://localhost:5173
Contributions are welcome! Feel free to fork the repository and submit a pull request.
MIT License. This project is open for use and modification under the terms of the MIT license.
