Picking up data from axios and vues

1

I have a very strange problem, I have the following code inside a VueJS component.

I'm developing a system where I choose the options through several checkboxes, and step the id of them for that my component below.

And I use the axios to make the request in the database and retrieving the data I need.

See below for the component.

<template>
    <div>
        <ul>
            {{ modulos_encontrados }}
        </ul>
    </div>
</template>

<script>

export default {
    props:['turmas_checked'],
    data () {
        return {
            modulos:[]
        }
    },
    computed:{
        modulos_encontrados(){
            if(this.turmas_checked.length > 0){     
                  axios.get('/modulos/${this.turmas_checked}')
                .then(response => {
                    this.modulos = response.data;
                });
            }
        }

    }
}
</script>

And if I call the this.modulos outside of then (), I have the result I want, but it stays in an infinite looping, making requests through the axios, and if I put it inside then of course it will not return anything.

Does anyone know how I can retrieve what I want from the axios result and list within that same component?

    
asked by anonymous 27.06.2018 / 02:52

1 answer

1

You should not use computed in this way, computed is ideal for synchronous logic and should be

Use watch to follow changes in turmas_checked and imediate: true to run watcher when component mounts.

The code could look like this:

<template>
  <div>
    <ul>
      {{ modulos_encontrados }}
    </ul>
  </div>
</template>

<script>
export default {
  props: ['turmas_checked'],
  data() {
    return {
      modulos: [],
    };
  },
  computed: {
    modulos_encontrados() {
      const length = this.modulos.length;
      return 'Encontrados ${length} modulo${length === 1 ? 's' : ''}.';
    },
  },
  watch: {
    message: {
      immediate: true,
      handler() {
        if (this.turmas_checked.length > 0) {
          axios.get('/modulos/${this.turmas_checked}').then((response) => {
            this.modulos = response.data;
          });
        }
      },
    },
  },
};
</script>
    
27.06.2018 / 08:52