In Vue.js, several methods exist for sharing data between components, depending on the relationship between components (e.g., parent-child, sibling, or completely decoupled) and the complexity of the data flow you require.
1. Props and Events
For parent-child relationships, the most common approach to share data is using props and events. The parent component transmits data to the child via props, while the child communicates with the parent by emitting events.
Example:
vue<!-- Parent component --> <template> <div> <child-component :parentData="data" @childEvent="handleChildEvent"/> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { data: 'This is parent component data' } }, methods: { handleChildEvent(value) { console.log('Data received from child component:', value); } } } </script>
2. Vuex
For multiple components or complex state management needs, Vuex is Vue's official state management library. It centralizes state storage across all components and ensures predictable state changes through defined rules.
Example:
vue// Vuex store const store = new Vuex.Store({ state: { sharedData: 'Shared data' }, mutations: { updateSharedData(state, data) { state.sharedData = data; } } }); // Component usage <template> <div>{{ this.$store.state.sharedData }}</div> </template>
3. provide / inject
Vue's provide / inject API enables ancestors to inject dependencies into all descendant components, regardless of hierarchy depth.
Example:
vue<!-- Ancestor component --> <script> export default { provide() { return { sharedData: 'This is the provided data' }; } } </script> <!-- Descendant component --> <script> export default { inject: ['sharedData'], mounted() { console.log(this.sharedData); // Output: This is the provided data } } </script>
4. EventBus
Although deprecated in Vue 3, EventBus was a common communication method in Vue 2, using an empty Vue instance as a central event bus for inter-component communication.
Example:
vue// event-bus.js import Vue from 'vue'; export const EventBus = new Vue(); // Emitting an event EventBus.$emit('updateData', 'New data'); // Listening for an event EventBus.$on('updateData', data => { console.log(data); });
Choosing the right method is critical based on your specific needs. For simple parent-child relationships, props and events may suffice, whereas for complex applications or state sharing across multiple components, Vuex or provide/inject are more suitable.