Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue js axios response to array list

Tags:

vue.js

axios

i am working a typeahead. and my typeahead accept a array list like ['Canada', 'USA', 'Mexico']. and now i have a axios api to get a list of country. but i don't know how can i convert to a array list. Now work if hardcode a country list.

<vue-bootstrap-typeahead
 :data="addresses"
 v-model="addressSearch"
/>
data() {
 return {
  addresses: ['Canada', 'USA', 'Mexico'],
  addressSearch: '',
 }
},
axios.get('api_link', {})
  .then(function (response) {
  //How can i create a array list from api return useing name like addresses?
})

And my api return: [ { "id": 1, "name": "Canada" }, { "id": 2, "name": "USA" }, ]

like image 326
Tommy Tang Avatar asked Nov 19 '25 12:11

Tommy Tang


1 Answers

Make use of the created() lifecycle hook to get the data:

created() {
  axios.get('api_link', {})
    .then((response) => { this.addresses = response.data.map(x => x.name) })
}

In your data() make sure to initialize to an empty array:

data() {
  return {
    addresses: [],
    ...
}

Just so you see what the map function does:

console.log([ { "id": 1, "name": "Canada" }, { "id": 2, "name": "USA" }, ].map(x=>x.name))
like image 163
connexo Avatar answered Nov 21 '25 05:11

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!