[Vuejs]-Vue Grid Data from REST Service

1👍

Not much. If you use some frontend framework (like Vuetify or Bootstrap-Vue) you may need to read the documentation and work according to what’s written, but with basic Vue something like this may answer your question:

new Vue({
  el: '#app',
  data: {
    users: []
  },
  computed: {
    userTable() {
      // actually inserting the HTML in the template
      return this.createTable(this.users)
    }
  },
  methods: {
    getUsers() {
      // getting JSON data from API
      return new Promise((resolve, reject) => {
        const users = fetch('https://jsonplaceholder.typicode.com/users')
          .then(response => response.json())
          .then(json => {
            resolve(json)
          })
      })
    },
    userRowHtml(user) {
      // creating a single table row of user data
      if (user) {
        let html = ''
        Object.entries(user).forEach(e => {
          if (e[0] !== 'address' && e[0] !== 'company') {
            html += `<td>${e[1]}</td>`
          } else {
            html += `<td>cannot display</td>`
          }
        })
        return html
      }
      return ''
    },
    userRows(users) {
      // creating the table rows for user data
      if (users && users.length) {
        let html = ''
        users.forEach(e => {
          html += `<tr>${this.userRowHtml(e)}</tr>`
        })
        return html
      }
      return ''
    },
    createTable(users) {
      // creating the table to insert
      if (users && users.length) {
        const headers = Object.keys(this.users[0])
        let html = ''
        html += '<table><thead><tr>'
        headers.forEach(e => {
          html += `<th>${e}</th>`
        })
        html += '</tr></thead>'
        html += '<tbody>'
        html += this.userRows(users)
        html += '</tbody></table>'
        return html
      }
      return ''
    }
  },
  async mounted() {
    this.users = await this.getUsers()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-html="userTable"></div>
</div>

This is just a simple example, using a mockup JSON API and doing nothing, only displaying the data in an HTML table. We could use templates, state management, etc. for a more complex environment – Vue is as developer-friendly as it gets nowadays. 🙂

Leave a comment