3
votes

I have created following vue component.

Following code is not updating data when I update after ajax response.

Is there any specific method I need to apply after updating data.

I am using class based vue cli 3 components. It is not giving any error also. Just data is not updating.

Is there any method we need to use for vue reactivity to update the data or mounted event don't work?

Even if I give empty array as children, Name is not updating.

<template>
      <el-tree :data="MyData" :props="defaultProps"></el-tree>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ElemUI from 'element-ui';
import axios from 'axios';

@Component({
  components: {
    ElTree: ElemUI.Tree,
  },
})
export default class In extends Vue {
  public MyData: any = [
          {
            label: 'Data',
            children: [],
          },
        ];
  public defaultProps: any = {
    children: 'children',
    label: 'label',
  };
  public mounted() {
    axios
      .post('https://localhost:44375/api/Graph', {
        query: `{
                myData {
                    name,
                    innerData {
                    name
                    }
                  }
                }`,
      })
      .then((response) => {
        this.MyData = [
          {
            label: 'Another Data',
            children: Response.data.data.AnotherArrayData
          },
        ];
      });
  }
}
</script>
1
recommend defining the axios call as a method, then calling the method in the mounted hook with this.methodName() The method should be an async that awaits axios to resolve, since it's a promise. - Len Joseph
@I'mOnlyVueman. Even if I dont use axios, data is not updating. This code if I copy to stackblitz, it is working. Dont know whats wrong with only my code. - Anonymous Creator
I tried creating another function and call it in mounted. still no luck. - Anonymous Creator
can you try switching mounted to created? That may make a difference, since created would trigger data retrieval before the DOM mounts. Also, make sure your axios call is written as an async / await, since it returns a promise. Something like async method(){ await axios... } .. last thing would be to console.log your response to make sure you're setting your data with actual data. Idk what your server level res.send looks like, but that could also be the issue. - Len Joseph
Yes...!!! Mounted To Created worked...!!! Thanks a lot man. Please add answer. :) - Anonymous Creator

1 Answers

2
votes

So to fix the issue, make axios call async and then load on a created hook, using

methods: {
   async fetchDataMethod() {
      await axios...
  }
}`

`created() {
   this.fetchDataMethod();
}

This will populate the response data prior to the virtual DOM mounting.