1

I'm curious and can't find where in Docs to explain this behavior

    <script setup>
    let formData = reactive({});
    
    // Method to be called when there is an emitterUIUpdate event emitted
    // from form-modal.vue @param(data) is the form data sent from the
    // form submission via the event bus. It is in the form of an object.
    // We will then send this data back
    // down to child display-scrap component via a prop.
    const updateUI = (data) => {
      console.log("emitter for updateUI");
      formData = data;
  
    };

Here formData is not reactive and cant pass value down via a prop to child. But this works as hoped

let formData = ref({});

const updateUI = (data) => {
  console.log("emitter for updateUI");
  formData.value = data;
  console.log("App FormData is", formData.value);
};

Now formData is reactive, and can pass it as a prop. Reading the docs over, if variable data is an object then I should be OK. I did notice if I moved formData up to global scope in first example then it would be reactive. Can anyone explain this behavior and why I had to use ref() to make my example work? Thanks.

mo3n
  • 1,522
  • 2
  • 10
  • 34
Alan
  • 1,067
  • 1
  • 23
  • 37

1 Answers1

1

Your initial attempt of using reactive doesn't work because you're simply re-assigning it. The correct way to mutate a reactive object is to re-assign its inner values.

const formData = reactive({})

const updateUI = (data) => {
  // Correct
  Object.assign(formData, data)

  // Incorrect
  formData = data 
}

Defining ref({}) is essentially { value: reactive({}) } and it works, in your case, because you're re-assigning the formData inner value.

However, if you treated the ref in the same manner in which you treated reactive, by re-assigning the variable, the outcome will be the same.

Cue
  • 2,699
  • 1
  • 12
  • 13
  • Thanks for explanation. Now it is working as expected. I'm curious, is the need for doing it this way because objects are stored by reference? – Alan Dec 28 '21 at 22:10
  • 1
    This might help you better understand it https://stackoverflow.com/questions/61452458/ref-vs-reactive-in-vue-3 – Cue Dec 29 '21 at 16:55
  • Thanks. In reading that I feel a little like when reading about this.something in JavaScript. – Alan Dec 29 '21 at 21:27