How to extract axios response data into variables in vuejs

hidar Source

I am trying to achieve the same functionality as the ...mapState() function in Vue.

I have an axios request that returns an object with different props, like this:

axios.get(
 '/'
).then(
 res => {
  console.log(res) // {name: 'foo', age: 22, height: '1.72m', job: 'developer'}
 }
)

Now, in the same way as ...mapState() can I extract the props so I can use them in my template like:

<template>
 <div> 
  Hello My name is {{name}} and I am {{age}} years old
 </div>
</template>

I was thinking about assigning the response object to the vuejs data, but I have other variables that I don't want to be re-written

javascriptvuejs2

Answers

answered 6 months ago Yakalent #1

you can try this:

axios.get(
 '/'
).then(
 res => {
  console.log(res) // {name: 'foo', age: 22, height: '1.72m', job: 'developer'}
  return { index: res}
 }
)

then you can access the data

<template>
 <div> 
  Hello My name is {{index.name}} and I am {{index.age}} years old
 </div>
</template>

comments powered by Disqus