gpt-4o-2024-08-06· openai
from WildChat-4.8M
shared state between two components vue 3
- User
shared state between two components vue 3
- Assistant
In Vue 3, there are several ways to manage shared state between two or more components. Here are some common approaches:
-
Prop drilling:
- If the components are parent-child, you can pass data from a parent component to a child component using props, and emit events from the child component to the parent to update the state.
Example:
vue<!-- ParentComponent.vue --> <template> <ChildComponent :sharedState="sharedState" @updateSharedState="updateSharedState" /> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const sharedState = ref('Hello World'); function updateSharedState(newValue) { sharedState.value = newValue; } return { sharedState, updateSharedState }; } }; </script> <!-- ChildComponent.vue --> <template> <input :value="sharedState" @input="$emit('updateSharedState', $event.target.value)" /> </template> <script> export default { props: ['sharedState'] }; </script> -
Provide/Inject API:
- This is suitable for passing data from a parent to deeply nested descendant components without prop drilling.
Example:
vue<!-- ParentComponent.vue --> <template> <ChildComponent /> </template> <script> import { provide, ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const sharedState = ref('Hello World'); provide('sharedState', sharedState); } }; </script> <!-- ChildComponent.vue --> <template> <input :value="sharedState" @input="updateSharedState($event.target.value)" /> </template> <script> import { inject } from 'vue'; export default { setup() { const sharedState = inject('sharedState'); function updateSharedState(newValue) { sharedState.value = newValue; } return { sharedState, updateSharedState }; } }; </script>
-