[Vuejs]-Vue not rendering fetched html

0👍

You’re approaching this in the traditional JavaScript way of manipulating the DOM directly. In Vue, we set state which can then be rendered by your template.

Instead:

  1. Create a data attribute to store your state
  2. Under methods, write a function to fetch your data, then update the components data
  3. Call your function in the components created hook
  4. In you’re template render the results
    • Don’t forget to check it’s present first, with v-if
    • You can use v-for to iterate over, and render lists

Here’s a working demo


I don’t have access to your API endpoint, so for demo purposes, am just using the GitHub API, to fetch and render a list of all repos in the Vue.js organization.

Here’s what it looks like:

Vue.config.devtools = false;
    Vue.config.productionTip = false;
    new Vue({
      el: '#app',
      name: 'dbzx10299-demo',
  data() {
    return {
      loaded: false,
      response: null,
    }
  },
  methods: {
    fetchData() {
      const demoEndpoint = 'https://api.github.com/orgs/vuejs/repos';
      fetch(demoEndpoint)
      .then(response => response.json())
      .then(data => {
        this.response = data;
        this.loaded = true;
      })
    },
  },
  mounted() {
    this.fetchData();
  },
    })
<script src="https://unpkg.com/vue@2.x/dist/vue.js"></script>

<div id="app">
<div class="hello">
  <h2>Vue Repo List - Data fetching example</h2>
  <div v-if="!loaded">Loading...</div>
  <ul v-else>
    <li v-for="(repo, index) in response" :key="index">
      <a :href="repo.html_url" :title="repo.description" target="_blank">
        {{ repo.name }}
      </a>
      <i>★ {{ repo.stargazers_count }}</i>
    </li>
  </ul>
</div>
</div>

Leave a comment