0
<template>
  <div class="comment">
    <div v-for="(comment, index) in comments" :key="index">
      {{ getUser(comment.student_idx) }}
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import server from '@/models/server'
export default {
  data() {
    return {
      url: server,
      comments: {}
    }
  },
  props: ['idx'],
  created() {
    axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
    .then(response => {
      if (response.data.status === 200) {
        this.comments = response.data.data.replies
      }
    })
  },
  methods: {
    getUser (idx) {
      axios.get(`${this.url}/member/student/${idx}`)
      .then(response => {
        if (response.data.status === 200) {
          return response.data.data.member.name
        }
      })
    }
  }
}
</script>

I would like to load the comments at created and print them out using v-for.

In v-for, I would like to load the member.name from each comment

But {{ getUser(comment.student_idx) }} is undefined.
I don't know how to return data from axios
Help me please!!

3
  • Vue templates only render actual data, not promises. You need to assign your axios response to a data() property, like comments, and then render that data property. Commented Feb 26, 2020 at 5:29
  • please, change the return json format. Commented Feb 26, 2020 at 5:57
  • I got it. Thanks for your comment Commented Feb 27, 2020 at 11:23

1 Answer 1

1

Your method should not be async for stable run code. My recomendation is next code:

<template>
  <div class="comment">
    <div v-for="(comment, index) in comments" :key="index">
      {{ comments['user'] }}
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import server from '@/models/server'
export default {
  data() {
    return {
      url: server,
      comments: []
    }
  },
  props: ['idx'],
  created() {
    axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
    .then(response => {
      if (response.data.status === 200) {
        this.comments = response.data.data.replies;
        if(this.comments)
          for(let comment of this.comments){
            this.getUser(comment, comment.student_idx);
          }
      }
    })
  },
  methods: {
    getUser (comment, idx) {
      axios.get(`${this.url}/member/student/${idx}`)
      .then(response => {
        if (response.data.status === 200) {
          this.$set(comment, 'user', response.data.data.member.name);
        }
      })
    }
  }
}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know how to do it. Thank you very much

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.