serkan
serkan

Reputation: 7151

vuejs - accessing dynamically created input on function call

<div v-if="result.length" style="clear:both">
      <div v-bind:key="item.id" v-for="item in result">
        <div class="ui form">
          <div class="field">
            <label>Content</label>
            <textarea name id cols="30" rows="10">{{item.content[0]}}</textarea>
          </div>
          <div class="field right aligned">
            <button v-bind:id="item.id" @click="updateData" class="ui primary button">Update</button>
          </div>
      </div>
</div>

have this iteration, id like to access to the value of 'current' text area on updateData function call. I thought assigning id to textarea input as $ref but seems kid of off. Ayn help is appreciated, thanks!

Upvotes: 0

Views: 297

Answers (2)

Steve
Steve

Reputation: 20469

You can use databinding for the textareas, and pass the current item to your update funtion:

Vue.config.productionTip = false; // suppress

new Vue({
    el: "#app",
    data: {
        result: [
           {id:0,content:['some content']},
           {id:1,content:['some content']},
           {id:3,content:['some content']},
        ]
    },
    methods:{
        updateData(item){
            alert(item.content[0]);
        }
    }
    
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
  <div v-bind:key="item.id" v-for="item in result">
    <div class="ui form">
      <div class="field">
        <label>Content</label>
        <textarea name id cols="30" rows="10" v-model="item.content[0]"></textarea>
      </div>
      <div class="field right aligned">
        <button v-bind:id="item.id" @click="updateData(item)" class="ui primary button">Update</button>
      </div>
  </div>
  
</div>

Upvotes: 0

Tristan De Oliveira
Tristan De Oliveira

Reputation: 808

Use refs array

You need to use the index value of the v-for

And access to the refs by the index

<div v-bind:key="item.id" v-for="(item, index) in result">

<textarea ref="textarea" name id cols="30" rows="10">{{item.content[0]}}</textarea>

<button v-bind:id="item.id" @click="updateData($refs.textarea[index])" class="ui primary button">Update</button>

Upvotes: 1

Related Questions