Location>code7788 >text

Vue Hook Wrapping Generic Forms

Popularity:975 ℃/2024-08-01 20:06:15

I. Requirements for the creation of generic forms

Implement a generic form component with the following functionality:

  1. Dynamic column configuration.
  2. Pagination function.
  3. Sorting function.
  4. Scalable line operation functions.

II. Designing general-purpose form components

First, a basic table component needs to be designed that accepts parameters such as column configuration, data and paging information.

1. CreationuseTable Hook

existsrc/hooks directory to create the Documentation:

import { ref, reactive, onMounted, toRefs } from 'vue';

export function useTable(fetchData) {
  const state = reactive({
    loading: false,
    data: [],
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    sort: {
      field: '',
      order: '',
    },
  });

  const loadData = async () => {
     = true;
    const { currentPage, pageSize } = ;
    const { field, order } = ;
    const result = await fetchData(currentPage, pageSize, field, order);
     = ;
     = ;
     = false;
  };

  const changePage = (page) => {
     = page;
    loadData();
  };

  const changePageSize = (size) => {
     = size;
    loadData();
  };

  const changeSort = (field, order) => {
     = field;
     = order;
    loadData();
  };

  onMounted(() => {
    loadData();
  });

  return {
    ...toRefs(state),
    loadData,
    changePage,
    changePageSize,
    changeSort,
  };
}

 

 

2. Creation

existsrc/components directory to create the Documentation:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="col in columns" :key="" @click="changeSort()">
            {{  }}
            <span v-if=" === ">{{  === 'asc' ? '↑' : '↓' }}</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in data" :key="">
          <td v-for="col in columns" :key="">{{ row[] }}</td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="changePage( - 1)" :disabled=" === 1">Previous</button>
      <span>{{  }} / {{ ( / ) }}</span>
      <button @click="changePage( + 1)" :disabled=" === ( / )">Next</button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useTable } from '@/hooks/useTable';

export default {
  props: {
    fetchData: {
      type: Function,
      required: true,
    },
    columns: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const { data, loading, pagination, sort, loadData, changePage, changePageSize, changeSort } = useTable();

    return {
      data,
      loading,
      pagination,
      sort,
      loadData,
      changePage,
      changePageSize,
      changeSort,
    };
  },
};
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>

 

III. Using Generic Form Components

In a real project, you can use this general-purpose form component in this way:

1. Creation subassemblies

existsrc/views directory to create the Documentation:

<template>
  <div>
    <TableComponent :fetchData="fetchData" :columns="columns" />
  </div>
</template>

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

export default {
  components: {
    TableComponent,
  },
  setup() {
    const columns = [
      { key: 'name', title: 'Name' },
      { key: 'age', title: 'Age' },
      { key: 'email', title: 'Email' },
    ];

    const fetchData = async (page, pageSize, sortField, sortOrder) => {
      // Analog Data Acquisition
      const total = 100;
      const data = ({ length: pageSize }, (v, i) => ({
        id: (page - 1) * pageSize + i + 1,
        name: `Name ${(page - 1) * pageSize + i + 1}`,
        age: 20 + ((page - 1) * pageSize + i + 1) % 30,
        email: `user${(page - 1) * pageSize + i + 1}@`,
      }));
      return { data, total };
    };

    return {
      columns,
      fetchData,
    };
  },
};
</script>

 

IV. Interpretation of codes

  1. defineuseTable Hook

    • Using Vue'sref cap (a poem)reactive Define the form state.
    • defineloadDatachangePagechangePageSize cap (a poem)changeSort functions to handle data loading and paging and sorting changes.
    • utilizationonMounted Lifecycle hooks load data when the component is mounted.
  2. defineTableComponent subassemblies

    • acceptancefetchData cap (a poem)columns as a component property.
    • utilizationuseTable Hook to get table data and manipulate functions.
    • Renders the form header, body, and paging components and binds related events.
  3. Using Generic Form Components

    • exist Define the column configuration and data fetch functions in the
    • utilizationTableComponent pass onfetchData cap (a poem)columns Properties.