In Vue.js, there are several ways to pass data between parent and child components. Here are some common methods:
Parent Component: You can pass data from a parent component to a child component using props. Define props in the child component, and then pass data to the child component in the parent template.
vue<!-- ParentComponent.vue --> <template> <ChildComponent :propName="parentData"></ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, data() { return { parentData: 'Hello from parent!', }; }, }; </script>
vue<!-- ChildComponent.vue --> <template> <div> <p>{{ propName }}</p> </div> </template> <script> export default { props: ['propName'], }; </script>
Child Component: Emit a custom event in the child component when an action occurs, and listen to that event in the parent component.
vue<!-- ChildComponent.vue --> <template> <button @click="emitEvent">Click me</button> </template> <script> export default { methods: { emitEvent() { this.$emit('childEvent', 'Data from child'); }, }, }; </script>
Parent Component: Listen to the custom event in the parent component and handle the emitted data.
vue<!-- ParentComponent.vue --> <template> <ChildComponent @childEvent="handleChildEvent"></ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, methods: { handleChildEvent(data) { console.log('Data from child:', data); }, }, }; </script>
Vuex Store: For complex state management or when passing data between distant components, consider using Vuex.
javascript// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
sharedData: 'Hello from Vuex!',
},
mutations: {},
actions: {},
getters: {},
});
Parent Component: Access the state from the Vuex store in the parent component.
vue<!-- ParentComponent.vue --> <template> <div>{{ $store.state.sharedData }}</div> </template>
Child Component: Similarly, access the state from the Vuex store in the child component.
vue<!-- ChildComponent.vue --> <template> <div>{{ $store.state.sharedData }}</div> </template>
Choose the method that best fits your application's requirements. For simple cases, props and custom events might be sufficient, while Vuex is more appropriate for managing shared state in larger applications.