MIHIR PATEL
MIHIR PATEL

Reputation: 53

Fetch the value of element dynamically in Vuejs

I'm not sure if this is the question directly relate to Vue or JavaScript, but as it involves 'refs' from VueJs, i have posted question here.

I've multiple input text elements in my DOM. They are named as txtScore1, txtScore2, txtScore3 etc. On my click button event I want to fetch the value from say txtScore1. But how can I pass this refernce dynamically in this.$refs.{{ #some way of referring txtScore1 dynamically# }}.value?

I'm creating input element as follows: <input v-bind:ref="'txtScore' + props.item.Id" type="text"/>

can you please help?

Thanks, Mihir

Upvotes: 0

Views: 1780

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

If you are stating to props data, then the following is a wrong way:

<input v-bind:ref="'txtScore' + props.item.Id" type="text"/>

You should just use item.Id.

To your question,

You need to pass the item object in your input handler:

<input v-bind:ref="'txtScore' + item.Id" type="text" @input="handler(item)" />

In your method:

methods: { // or, whatever you need
  handler(item) {
    //use ref value like this:
    //this.$refs['txtScore' + item.id].value
  }
}

But, this is really unnecessary, you can simply use the $event object instead of using $refs:

<input type="text" @input="handler($event)" />

And then, just use the following:

handler(event) {
   console.log(event.target.value);
}

And even more, why don't you simply use v-model?

<input type="text" v-model="item" />

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135752

You can use string concatenation and the object property accessors/bracket notation as follows:

new Vue({
  el: '#app',
  data: {
    props: {item: {Id: 11, value: "Click me"}}
  },
  mounted: function() {
    var someVar = 11;
    console.log("11:", this.$refs['txtScore' + someVar].value);
  },
  methods: {
    goClick(Id) {
      console.log('You have clicked '+ Id + ', with value: "' + this.$refs['txtScore' + Id].value + '"');
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
  <input v-bind:ref="'txtScore' + props.item.Id" type="text" v-model="props.item.value" @click="goClick(props.item.Id)" />
</div>

Though you probably won't need it:

new Vue({
  el: '#app',
  data: {
    props: {item: {Id: 11, value: "Click me"}}
  },
  methods: {
    goClick(item, value) {
      console.log('Clicked item '+ item.Id + ', with value: "' + value + '"');
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <input type="text" v-model="props.item.value" @click="goClick(props.item, $event.target.value)" />
</div>

Upvotes: 0

Related Questions