[Vuejs]-VueJS – Update Parent Data After Ajax

-1👍

If you share the AJAX part of code, maybe I can help better, but IMHO I think that the easiest way is emiting a event from children, and catch it with the parent element when the AJAX call is done (success or error).

Events provide a way to inform your parent components of changes in children.

Template Usage:

<my-component v-on:myEvent="parentHandler"></my-component>
<!-- Or more succinctly, -->
<my-component @myEvent="parentHandler"></my-component>

Firing an Event:

...
export default {
  methods: {
    fireEvent() {
      this.$emit('myEvent', eventValueOne, eventValueTwo);
    }
  }
}

Additionally, you can create global event buses to pass events anywhere in your app

Extracted from here.

Edit

Ok, I didn’t understand you well, if you have problems sending data down from parent to children when updating the parent the proper way is the double data binding.

Maybe your problem is that the data is only evaluated in component creation, and your child will be created with the initial value of the parent component…

You can try some different things to solve this, like:

1 – Maybe your issue is related to a change detection caveat

Maybe you’re creating a new property in an object…

 _parentData = response

…when you should do…

_parentData.$set('someObject.someProperty', someValue)

2 – Use watch on parent instead of created:

 watch:{ 
  yourData() {
        $.ajax({
            url: '/someUrl/',
            content_type: 'application/json',
            data_type: 'json',
            success: function(response) {
                 _parentData = response
            }
         })
  },

3 – Try using .sync ( deprecated in 2.0 ):

<component :something.sync="variable"></component>

4 – Bind .this to the anonymous AJAX call or use arrow functions as @Bert commented:

success: () => (response) {
                 _parentData = response
            }

Hope it helps!

Leave a comment