问题
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)
回答1:
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: "john@doe.com"
});
}
return { form, setForm, resetForm };
}
See it live on codesandbox
credits: taken from here
回答2:
Citing from the official Vueland Discord server:
"For what I know, reactive is the old way we use to do reactivity from the Classic API, so to reset the values should be something like:"
const myData = reactive({
foo: true,
bar: ''
})
function resetValues () {
myData.foo = true
myData.bar = ''
}
Therefore, if you don't change properties you should be able to use Object.assign()
. (Correct me if I'm wrong)
来源:https://stackoverflow.com/questions/61184749/how-to-properly-reset-vue-composition-apis-reactive-values