Home > Back-end >  How to retrieve updated input value in loop
How to retrieve updated input value in loop

Time:12-07

I have this html:

<div v-for="item in my_items">
    <div>
      <input type="text" :value=item.name />
    </div>
    <div>
      <button @click="edit(item.id, item.name)">Edit</button>
    </div>
  </div>

And then this javascript:

export default {
    data() {
        return {
            my_items: []
        }
    },
    methods: {
        async edit(id, name){
            console.log("edit", id);
            console.log("name", name);
        },
    },
    async mounted() {
        this.my_items = [
            {id: 1, name: 'name1'}  
            ,{id: 2, name: 'name2'} 
        ];
    }
}      

So when component is mounted, two rows will be displayed: "name1" and "name2". Along with a button to edit it. When i write something else in the input field and then click on the edit button, in the console I still see the "old" name for the variable. How can I access the current value in the input field from the function "edit()"?

CodePudding user response:

You can use v-model or else you need @input along with :value:

const app = Vue.createApp({
  data() {
    return {
      my_items: []
    };
  },
  mounted() {
    this.my_items = [{id: 1, name: 'name1'}, {id: 2, name: 'name2'} 
    ];
  },
  methods: {
    edit(item) {
      console.log("item", item);
    },
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="item in my_items" :key="item.id">
  <div>
    <input type="text" v-model="item.name" />
  </div>
  <div>
    <button @click="edit(item)">Edit</button>
  </div>
</div>
</div>

  • Related