1

How can I assign the value retrieved from axios to v-text-field

I have this in my template:

<v-text-field
   v-model="name"
   label="Name"></v-text-field>

    <script>
    import axios from 'axios';

    export default {
      data() {
        return {
          name: '' // <= how will I assign the value here from axios response?
        }
      },
      asyncData ({ params }) {
        return axios.get(`my-url`)
        .then((response) => {
          return { user: response.data.data.results[0] };
        });
      }
    }
</script>
2
  • How do you call asyncData()? Commented Nov 7, 2018 at 15:52
  • @ittus It's automatically called when the vue page loaded. I can also get the results from response. What I would like to do is assign the user's name to data() name attribute Commented Nov 7, 2018 at 15:55

2 Answers 2

2

I'm assuming that you are using NUXT (from the asyncData method).

The data you return from the asyncData method is merged into the data of your component.

You should do the following:

<template>
    <v-text-field
            v-model="name"
            label="Name"></v-text-field>
</template>

<script>
    import axios from 'axios';

    export default {
        data() {
            return {}
        },
        asyncData ({ params }) {
            return axios.get(`my-url`).then((response) => {
                return { name: response.data.data.results[0].name };
            })
        }
    }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

On my terminal I keep getting ✖ error TypeError: Cannot read property 'results' of undefined
1

How about using the created hook?

created() {
   this.name = this.user.name
}

1 Comment

Thanks @Husam Ibrahim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.