Passing Objects in Nuxt
2025-01-08
// composables/useSharedState.ts
export const useSharedState = () => useState('sharedObject', () => ({
// Initial obj props
}))
Use in any component requiring access to the shared object:
<script setup>
const sharedObject = useSharedState()
</script>
<script setup>
const sharedObject = useSharedState()
function updateObject() {
sharedObject.value = { ...sharedObject.value, newProperty: 'New Value' }
}
</script>
<template>
<ChildComponent :props="props" @method="signUp"/>
</template>
<script setup>
const props = {
fields: [
"email",
"password",
"confirm",
],
header: "Register a new account",
button: [
{
text: "Sign Up",
color: "green-500",
}
]
};
function signUp(email) {
console.log(email)
}
</script>
In the child component (ChildComponent.vue):
<script setup>
const { props } = defineProps(['props']);
</script>
Child component:
<script setup>
const emit = defineEmits(['method']);
function sendDataToParent(data) {
emit('method', data);
}
</script>
The child component can now call sendDataToParent with the data it wants to send to the parent.
Parent component can receive data in the method it passed to the child:
<script setup>
function signUp(email) {
console.log(email)
}
</script>
Â