umma.dev

Components and API Calls in Vue

Vue components are split into three parts, template, script and style. This post explains how to import components, the general structure of vue apps and how to get data in the front-end via an API.

The previous post explains how to get started. The default app structure will be used in this post.

Creating and Importing a Component

Within the src folder there is a folder called components. You should be able to see a file caled HelloWorld.vue, which is used when the server is started and the index page is displayed.

Create a new file within components and name it <file-name.vue>.

Add the following code and modify to suit the needs of your app.

<template>
    <div id="test">
        <p>Hello!</p>
    </div>
</template>

<script>
export default {
    name: 'component-name',
}
</script>

<style scoped>
p {
    color: red;
}
</style>

To export this component, open up App.vue in the src folder. Replace the code with the code below.

<template>
    <div id="app" class="small-container">
        <your-component />
    </div>
</template>

<script>
import YourComponent from '@/components/YourComponent';

export default {
    name: 'app',
    components: {
        YourComponent
    }
}
</script>

<style></style>

API calls in Vue

I am going to give an example of an employee table which takes fills the data via a mock API.

App.vue

<template>
    <div id="app" class="small-container">
       <employee-table :
       employees="employees"
       />
    </div>
</template>
<script>
import EmployeeTable from '@/components/EmployeeTable.vue';

export default {
  name: 'app',
  components: {
    EmployeeTable,
  },
  methods: {
    async getEmployees() {
      try {
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/users'
        );
        const data = await response.json();
        this.employees = data;
      } catch (error) {
        return error;
      }
    }
  },

  data() {
    return {
      employees: []
    };
  },
  mounted() {
    this.getEmployees();
  },

};
</script>
<style scoped></style>

EmployeeTable.vue

<template>
  <div id="employee-table">
    <table>
      <tbody>
        <tr v-for="employee in employees" :key="employee.id">
          <td>{{ employee.name }}</td>
          <td>{{ employee.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: 'employee-table',
  props: {
    employees: Array
  },
  data() {
    return {
      editing: null
    };
  }
};
</script>

<style scoped></style>