hidar
hidar

Reputation: 5939

How to extract axios response data into variables in vuejs

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

Upvotes: 0

Views: 1214

Answers (1)

Yakalent
Yakalent

Reputation: 1152

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>

Upvotes: 1

Related Questions