How to properly reset Vue Composition Api's reactive values

大憨熊 提交于 2020-08-08 04:23:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!