Recover select value with Vuejs

Asked

Viewed 1,032 times

1

i have a form and would like in the field (which is a select) to return (selected) the value previously marked.

Ex: if my selected is empty, the select will display values normally (1, 2, 3, 4). If, it has value, my select will show all values, but will come with the selected value 2 already.

<select v-model="item" style="height: 40px;">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
 </select>


data(){
   return{
      item: ''
   }
},
mounted(){
   this.api()
},
methods: {
   api(){
      axios.get(url)
      .then(response => {
         this.item = response.data.select  
      }
   }
}
  • Can you explain better what you mean by "the value previously marked"? You mean it’s in the database? Or written somewhere?

  • @Sergio yes, this is filled in the item, ai case it comes from the marked base, it fills in the item, if it comes empty from the base, it will keep the item empty.

  • Okay, and how you pass server data to Javascript?

  • @Sergio Atualizei o codigo

1 answer

2


You should have those option to be generated by the template, so it is easy to check whether the option to be generated is the one that must be chosen.

Something like that:

<select v-model="item" style="height: 40px;">
    <option 
       v-for"option in options" 
       selected="{{option == item}}"
    >
    {{option}}
    </option>
</select>


data(){
   return{
      item: '',
      options: ['1', '2', '3', '4']
   }
},
  • It worked, thanks :D one question, don’t you have any JS Course out there? or book? rsrs Hugs

  • @Rafaelaugusto here is learned a lot, exact as you did :)

  • In theory, the v-model in select should be able to mark the current item.

  • @bfavaretto will be? even if the "option" are in full?

  • Yes

  • @Rafaelaugusto @bfavaretto is right. Actually your code should work. You can check to see if it’s a problem if you are giving numbers to v-model when it uses strings to compare?

  • 1

    I think the problem should be in the API answer. But I would need to see the actual code, I think the question example is not the real one. Starting with the url that is used but not defined.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.