When passing a prop user
from the parent component to the child component, I want to create a separate copy of it without altering the original prop value.
I attempted to achieve this with the following code:
export default defineComponent({
props: {
apiUser: {
required: true,
type: Object
}
},
setup(props) {
const user = ref(props.apiUser);
return { user };
}
});
However, modifying the user object also ends up changing the apiUser prop. I considered using Object.assign
, but then the reactivity of the ref is lost.
In Vue 2.0, I would approach it like this:
export default {
props: {
apiUser: {
required: true,
type: Object
}
},
data() {
return {
user: {}
}
},
mounted() {
this.user = this.apiUser;
// Now I can use this.user without altering this.apiUser's value.
}
};
Credit goes to @butttons for providing the helpful suggestion that led to the solution.
const user = reactive({ ...props.apiUser });