Search code examples
vue.jsaxiosdropdown

Vue with Axios drop down pre populate


I'm trying to figure out how to pre-populate my vue drop down.

When I click on the drop down it doesn't show anything, but when I click off of it and back on it, it will show the options. This is not the behavior I want. I would like it to show the options when clicking on it once.

 <template>
  <select  v-model='selectedApp' @click="populateApp(results)">
  <option value="" disabled> Select an application</option>
  <option v-for="result in results">{{ result.name }} {{result.id}}</option>  
 </select>
</template>
<script>

import axios from 'axios'

 export default{
  data(){
   return {
    selectedApp: '',
    results: []
   }
  },
  methods: {

      populateApp: function(event){
      axios.get('/apdata',{params: {query: this.query}})
      .then(response => {
      this.results = response.data;
      console.log(this.results);
     });
   
   }
  }
 }

</script>

Thanks for you help!


Solution

  • You can do something like this. And you forgot to bind the value to option. Here's sample

    <template>
        <div>
          <select v-model="selectedApp">
            <option selected disabled value="">Choose</option>
            <option v-for="result in results" :value="result.id">{{ result.name }} {{ result.id }}</option>
          </select>
          <div>selectedApp: {{ selectedApp }}</div>
        </div>
     </template>
    
    export default {
      data() {
        return {
           selectedApp: "",
           results: []
        }
      },
      async mounted() {
        try {
           const response = await axios.get('/apdata', { params: { query: this.query } })
           this.results = response.data
        } catch(err) {
          console.log(err)
        }
      }
    }