I'm wondering how should I reset a reactive in vuejs setup? (i know if change it to the ref and using view.value will solve this problem, but there should be an answer to this for using reactive)
Reactivity is a key pillar for building VueJS applications. Vue 3 Reactivity with Composition API is driven by reactive() and ref() functions. These functions turn the component model data reactive so that Vue is able to track changes. However, both reactive() and ref() have their specific use-cases.
Vue's reactivity system works by deeply converting plain JavaScript objects into reactive proxies. The deep conversion can be unnecessary or sometimes unwanted when integrating with external state management systems (e.g. if an external solution also uses Proxies).
Conclusion. There's no harm in creating a simple module for global reactive state using Composition API in a small project, or if it's really important to avoid any overhead.
Thankfully, Vue 3 Reactivity with Composition API is equally robust. Vue 3 Reactivity with Composition API is driven by reactive () and ref () functions. These functions turn the component model data reactive so that Vue is able to track changes. However, both reactive () and ref () have their specific use-cases.
Let’s start with the basics: you must use ref () to create a reactive primitive value. reactive (), on the other hand, can only be used for creating reactive objects. You can use it as a replacement for the old data option in standard Option API-based Vue components, for example.
We can use reactive () API to only declare objects, arrays or other collection types such as Map or Set. Basically, reactive () function does not work for primitives such as string, integer, boolean etc. In my view, this is a big disadvantage that limits the use of reactive () API.
Object.assign
didn't work for me. (Maybe because I used a shim for the Composition API in Nuxtjs 2?) For anybody that run into the same problem: I had to use a compact loop.
setup() {
const initialState = {
name: "",
lastName: "",
email: ""
};
const form = reactive({ ...initialState });
function resetForm() {
for (const [key, value] of Object.entries(initialState)) {
form[key] = value
}
}
function setForm(values = {name: "John", lastName: "Doe", email: "[email protected]"}) {
// only loop with the supported keys of initial state
for (const key of Object.keys(initialState)) {
form[key] = values[key]
}
}
return { form, setForm, resetForm };
}
You can use Object.assign
:
setup() {
const initialState = {
name: "",
lastName: "",
email: ""
};
const form = reactive({ ...initialState });
function resetForm() {
Object.assign(form, initialState);
}
function setForm() {
Object.assign(form, {
name: "John",
lastName: "Doe",
email: "[email protected]"
});
}
return { form, setForm, resetForm };
}
See it live on codesandbox
credits: taken from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With