[Vuejs]-Getting a single array from an array of object

0πŸ‘

βœ…

At first create a state in data and name it sourceId,
then bind it to select <select v-model="sourceId" class="form-control">.

Now we need a computed filed which returns the source return this.sources.find(s => s.id === this.sourceId)

<template>
  <div class="sourceselection">
    <div class="jumbotron">
      <h2><span class="glyphicon glyphicon-list"></span> News List</h2>
      <h4>Select News Source</h4>
      <select v-model="sourceId" class="form-control">
        <option v-for="source in sources" :value="source.id" :key="source.id">
          {{ source.name }}
        </option>
      </select>
    </div>
    <div v-if="source">
      <h6 >{{ source.description }}</h6>
      <a v-bind:href="source.url"></a>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SourceSelection',
  data () {
    return {
      sources: [],
      sourceId: ''
    }
  },
  computed: {
    source () {
      return this.sources.find(s => s.id === this.sourceId)
    }
  },
  created() {
    this.$http.get('https://newsapi.org/v2/sources?language=en&apiKey=cf0866b5aaef42e995f9db37bb3f7ef4')
      .then(response => {
        this.sources = response.data.sources;
      })
      .catch(error => console.log(error));
  }
}
</script>

0πŸ‘

Instead of using an event handler you can bind the selected value directly to your source data.

here is a demo:

Vue.config.devtools = false
Vue.config.productionTip = false

new Vue({
  el: '#app',
  data() {
    return {
      sources: [{
        id: '1',
        description: 'one desc',
        name: 'one'
      }, {
        id: '2',
        description: 'two desc',
        name: 'two'
      }, ],
      source: ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select class="form-control" v-model="source">
    <option v-bind:value="source" v-for="source in sources" :key="source.id">{{source.name}}</option>
  </select>
  <h6>{{ source.description }}</h6>
</div>

Leave a comment