Creating Generic Data Table Using Vue.js

Generic Data Table :

Step1: Install the following packages in vue.js

npm install --save vue-good-table

Step: 2 Create a new file GoodDataTable.vue and add the following in it:

<template>
  <div>
    <vue-good-table :rows="rows" :columns="columns">
      <template slot="table-row" slot-scope="props">
        <span
          v-if="props.column.useRenderer"
          v-html="props.column.renderer(props.row)"
        />
      </template>
    </vue-good-table>
  </div>
</template>

<script>
import { VueGoodTable } from "vue-good-table";

export default {
  components: {
    VueGoodTable,
  },
  props: {
    columns: {
      type: Array,
      default: () => [],
    },
    apiEndpoint: {
      type: String,
      default: "data",
    },
  },
  data() {
    return {
      rows: [],
      uri: "https://localhost:44368/api/",
    };
  },
  mounted() {
    this.dataFetch();
  },
  methods: {
    dataFetch() {
      fetch(`${this.uri}${this.apiEndpoint}`)
        .then((res) => res.json())
        .then((res) => {
          if (res) this.rows = res;
        });
    },
  },
};
</script>

Step: 3 Open Employee.vue and add the following in it:

<template>
  <div class="container">
    <div class="card">
      <div class="card-header">
        <h1>Employee Details</h1>
      </div>
      <div class="card-body">
        <router-link to="/addEmployee" class="btn btn-primary" exact
          >Create</router-link
        >
        <good-data-table
          :apiEndpoint="'Employee/GetAllEmployees'"
          :columns="orderColumns"
        />
      </div>
    </div>
  </div>
</template>
<script>
import GoodDataTable from "./GoodDataTable.vue";
export default {
  components: { GoodDataTable },
  data() {
    return {
      employees: [],
      orderColumns: [
        {
          label: "Employee Name",
          field: "employeeName",
        },
        {
          label: "Department",
          field: "departmentName",
        },
        {
          label: "Salary",
          field: "salary",
        },
        {
          label:"ProfileImage",
          field:"profileImage",
          useRenderer: true,
          renderer: props => {
            if (props.profileImage) {
              return `<img src="${props.profileImage}" alt="${props.employeeName}" height="80" width="80" />`
            }
            return ''
          },
        }
      ],
    };
  },
};
</script>

Step: 4  Run project:

npm run serve

Code in action:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories