Home > Enterprise >  v-for doesn't get his options on mounted
v-for doesn't get his options on mounted

Time:09-27

I have a problem with a v-for. I make a call to an API and retrieve the data but the v-for is not updated.

Here my html :

<input list="listenomspartenaires" id="inputlistenomspartenaires" type="text" name="nominputlistenomspartenaires">
        <datalist id="listenomspartenaires">
           <option v-for="partenaire in listedespartenaires" :value="partenaire.nom" :key="partenaire.idpartenaire" :data-idpartenaire="partenaire.idpartenaire" />  <!--  -->
</datalist>

and my JS :

<script lang="js">
    import { defineComponent } from 'vue';

    export default defineComponent({
        data() {
            return {
                listedespartenaires : []
            };
        },
        methods:{            
            SetNoms(lesnoms){
                this.listedespartenaires = lesnoms;
                alert(lesnoms);
            }
        },
        mounted() {
            fetch("https://localhost:7264/api/partenaires/GetNoms")
                .then((response) => response.text())
                .then((data) => this.SetNoms(data));
        }
    });
</script>

The alert shows the data so they are well retrieved but my input is void.

I also tried to assign "listedespartenaires" directly from the fetch without passing by a method but the result is the same.

And I also tried this.$forceUpdate(); after having assigned "listedespartenaires". but it didn't work.

Can someone help me ?

Thank you,

Philippe

CodePudding user response:

Try to JSON.parse() your response:

const app = Vue.createApp({
  data() {
    return {
      listedespartenaires : [],
      selected: null
    };
  },
  methods:{            
    setNoms(lesnoms){
      this.listedespartenaires = JSON.parse(lesnoms);
      //alert(lesnoms);
    }
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.text())
      .then((data) => this.setNoms(data));
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <select id="listenomspartenaires" v-model="selected">
    <option v-for="partenaire in listedespartenaires" :value="partenaire.id">
      {{ partenaire.name }}
    </option>
  </select>
  {{ selected }}
</div>

  • Related