Cat Named Dog
Cat Named Dog

Reputation: 1698

Vue: Updating data on child component via ref not updating DOM

Inside my Child Component, I have this object in my data:

export default {
  
  name: 'BillingStripeForm',
  components: {
      Alert
  },

  data() {
      return {
        paymentFormError: {},

  }
...
}

And inside this child component, I'm using another component to display an error message based on a condition:

<Alert v-if="paymentFormError.description" :description="paymentFormError.description" :title="paymentFormError.title" type="error"></Alert>

The form logic is submitted by the parent component.

Since I need the child's data, I've given it a ref:

<billing-stripe-form ref="billingForm">

When I submit the form, I'm grabbing the component via refs and its data:

let billingFormComponent = this.$refs.billingForm;

Now I will manipulate the data on the child like so:

billingFormComponent.paymentFormError.description = "some error";
billingFormComponent.paymentFormError.title = "Oops! Something went wrong.";
// called on form submit
submitForm() {
  let billingFormComponent = this.$refs.billingForm;

  let billingAccount = billingFormComponent.billingForm;
  let stripe = billingFormComponent.stripe;
  let stripeElements = billingFormComponent.stripeElements;
  
  // just testing errors regardless
  billingFormComponent.paymentFormError.description = "some error";
  billingFormComponent.paymentFormError.title = "Oops! Something went wrong.";
}

Looking above, you will see that my Alert is shown if the object has a description, which I've just set.

In vue dev tools, I can see that the data is changing correctly. The child component data reflects what my submitForm function changes it to. But the DOM doesn't update. The Alert is not shown.

If I refresh the page and manually add the data via Vue Dev Tools, my Alert does show.

So how can I update a child's data via refs on the Parent, and have it be reactive and update the DOM?

Upvotes: 0

Views: 1359

Answers (1)

RicardoAgra
RicardoAgra

Reputation: 680

In order to update some part of Vue state in a reactive way, use Vue.set(this.data.object, 'propertyKey', 'value'). In your case:

Vue.set(billingFormComponent.paymentFormError, 'description', 'some error');

Upvotes: 2

Related Questions