T.A.
T.A.

Reputation: 640

Need To Access an Array of Objects with Vue.js

When the user selects a machine, I get the id of the machine. From that id I need to get the make and model of the machine.

    <ul class="list-unstyled">
          <li>
              <div v-for="dosimeter in dosimeters">
                 <label>
                    <input type="radio" name="optDosimeter" v-model="dosimeter_id" :value="dosimeter.id" v-on:click="dosimeter_select">{{dosimeter.nickname}}
                 </label>
              </div>
           </li>
     </ul>

Vue.js

    export default {
        data: function() {
            return {
              dosimeters:[],
              dosimeter_id:''
       }
     },
     mounted(){
        axios.get('/dosimeters').then((response) => {
                this.dosimeters=response.data;
            });
     },
     methods: {
         dosimeter_select(){
                not sure what to put here
            }
     }
  }

Upvotes: 0

Views: 1661

Answers (4)

T.A.
T.A.

Reputation: 640

I made some changes now it works. I used the suggestion from Boussadjra Brahim:

dosimeter_select(){
      let found= this.dosimeters.find(d=>{
            return d.id==this.dosimeter_id
        });

     console.log(found.make);
     console.log(found.model);
    }

and rather than using radio buttons I made it a select drop down. Also, rather than triggering the method with @click, I used @change.

Upvotes: 0

Christian Carrillo
Christian Carrillo

Reputation: 2761

it should work:

new Vue({
  el: "#app",
  data: {
    dosimeters:[
      { id: 1, name: 'foo' },
      { id: 2, name: 'bar' }
    ]
  },
  methods: {
  	dosimeterSelected (selectedDosimeter) {
    	console.log(`i doing something with dosimeter.id: ${selectedDosimeter.id}`)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul class="list-unstyled">
    <li v-for="dosimeter in dosimeters">
      <div>
        <label>
          <input type="radio" name="optDosimeter" :value="dosimeter.name" v-on:click="dosimeterSelected(dosimeter)">{{dosimeter.name}}
        </label>
      </div>
    </li>
  </ul>  
</div>

Upvotes: 0

ahmed galal
ahmed galal

Reputation: 269

try this

dosimeter_select()
{
 let machine =  this.dosimeters.find(dosimeter => dosimeters.id===this.dosimeter_id);
  // now you have the machine object
}

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

i think you should do something like :

  dosimeter_select(){
          let found= this.dosimeters.find(d=>{
                return d.id==this.dosimeter_id
            });

         console.log(found.make);
         console.log(found.model);
        }

Upvotes: 1

Related Questions