1

I am trying to list a set of posts from an API on a page using VueJS and Axios. The issue I am facing is one piece of the data (the post url) needs to be retrieved with a separate API call for that specific post and they provide the url for that data in the initial API call. I have the first part working perfectly, but I can't get the href to render in the view when the value is showing up in the Vue devtools.

JS

const vm = new Vue({
  el: '#app',
  data: {
    posts: []
  },
  mounted() {
    this.getPosts();
  },
  methods: {
    getPosts() {
      axios.get("api_url")
      .then((response) => {
        this.posts = response.data.posts;
        // Get URL for each post from separate API call
        this.posts.map(post => {
          axios.get(post.details_url+"&output=json")
          .then((response) => {
            post.official_url = response.data.post.pet_details_url;
          }).catch( error => { console.log(error); });
        });
      }).catch( error => { console.log(error); });
    }
  }
});

HTML

<div id="app">    
  <div v-for="post in posts">
    <a :href="post.official_url"> //href won't render
      <h2>{{ post.title }}</h2>
      <p>{{ post.text }}</p>
    </a>
  </div>
</div>

Data showing up in Vue DevTools

4
  • Add <div v-for="post in posts" :key="something_unique"> may solve your problem Commented Jul 30, 2018 at 4:26
  • Thanks for the suggestion @TruongDang, adding a key didn't help though. :/ Commented Jul 30, 2018 at 4:42
  • Look weird, I always use href like this :href= "`/${post.official_url}`" and it work. Make sure your post.official_url is not null :"( Commented Jul 30, 2018 at 4:54
  • I changed it to that formatting and now the href is showing up but I'm getting, <a href="undefined"></a>. So I think my issue has more to do more with how I am setting it in the JS. Commented Jul 30, 2018 at 5:25

1 Answer 1

4

It might be reactive problem. You can try Vue.set

getPosts() {
    let vm = this
    axios.get("api_url")
    .then((response) => {
      this.posts = response.data.posts;
      // Get URL for each post from separate API call
      
      this.posts.map((post, index) => {
        axios.get(post.details_url+"&output=json")
        .then((response) => {
          post.official_url = response.data.post.pet_details_url;
          Vue.set(vm.posts, index, JSON.parse(JSON.stringify(post)))
        }).catch( error => { console.log(error); });
      });
    }).catch( error => { console.log(error); });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This fixed my problem. Also, thank you for linking the explanation, I am still learning VueJS so this is much appreciated info.

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.