Home > Enterprise >  VueJS : Get my variable to update when I update my input/select
VueJS : Get my variable to update when I update my input/select

Time:01-22

Here's basically what my code looks like (or at least part of it, I tried to make it as simple as possible so you can understand what's my problem here. I have this json of selected ingredients that looks like this:

//var selected_ingredients = [{ 'uuid': uuid, 'nom': 'chicken', 'quantite': '500', 'unite': 'g'}, {...}]


<div
    v-for="(ingredient) in selected_ingredients"
    :key="ingredient.uuid"
>
    <input
        type="text"
        :value="ingredient.quantite"
    >

    <select
        :value="ingredient.unite"
    >
        <option
            v-for="unite in liste_unites"
            :key="unite"
            :value="unite"
        >{{ unite }}</option>
    </select>
</div>

</script>
export default {
data: function () {
    return {
        categories: [],
        tags: [],
        ingredients: [],
        selected_tags: {},
        selected_ingredients: [],
        liste_unites: ['pièce', 'mL', 'g']
    }
}
</script>

The thing is, I expected that by putting :value="ingredient.quantite", my quantite variable in selected_ingredients would update whenever I update the input field. Which is does not, and I can't seem to understand why. I've been doing some research but I can't tell if my logic is wrong or if I missed a detail. Can somebody please help me?

CodePudding user response:

Try with 2-way binding v-model:

const app = Vue.createApp({
  data() {
    return {
      selected_ingredients: [{ 'uuid': 1, 'nom': 'chicken', 'quantite': '500', 'unite': 'g'}, { 'uuid': 2, 'nom': 'chicken', 'quantite': '300', 'unite': 'mL'}],
      categories: [],
      tags: [],
      ingredients: [],
      selected_tags: {},
      liste_unites: ['pièce', 'mL', 'g']
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(ingredient) in selected_ingredients" :key="ingredient.uuid">
    <input type="text" v-model="ingredient.quantite">
    <select v-model="ingredient.unite">
      <option
          v-for="unite in liste_unites"
          :key="unite"
          :value="unite"
      >{{ unite }}</option>
    </select>
  </div>
  {{selected_ingredients}}
</div>

CodePudding user response:

Make sure Vue knows that you want ingredient.quantite to be reactive

Currently you have not done that.

To fix this, try moving your definition of selected_ingredients to within the data function:

data: function () {
return {
    selected_ingredients:[{ 'uuid': uuid, 'nom': 'chicken', 
                 'quantite': '500', 'unite': 'g'}, {...}],
    categories: [],
    tags: [],
    ingredients: [],
    selected_tags: {},
    selected_ingredients: [],
    liste_unites: ['pièce', 'mL', 'g']
  }
}
  • Related