0

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()"?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.