經典前端+後端+表頭+表身的開發實戰參考簡易模板【珍藏】

侬侬发發表於2024-09-13

前端部分(Vue 3 + Element Plus)

1. 修改 MPS002HList.vue(主生產計劃列表)

a. 新增查詢表單

在模板中新增查詢表單,包含產品料號、品名、規格和年月的輸入項。

<template>
  <div>
    <!-- 查詢表單 -->
    <el-form :inline="true" :model="filters" class="demo-form-inline">
      <el-form-item label="產品料號">
        <el-input v-model="filters.bo_no" placeholder="請輸入產品料號"></el-input>
      </el-form-item>
      <el-form-item label="品名">
        <el-input v-model="filters.item_name" placeholder="請輸入品名"></el-input>
      </el-form-item>
      <el-form-item label="規格">
        <el-input v-model="filters.item_spec" placeholder="請輸入規格"></el-input>
      </el-form-item>
      <el-form-item label="年月">
        <el-date-picker
          v-model="filters.mps_ym"
          type="month"
          placeholder="選擇年月"
          format="yyyy-MM"
          value-format="yyyy-MM"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchMpsList">查詢</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 生產計劃列表 -->
    <el-table :data="mpsList" style="width: 100%" v-loading="loading">
      <el-table-column prop="mps_no" label="單號" width="180">
        <template #default="{ row }">
          <el-button type="text" @click="showMpsDetails(row.mps_no)">
            {{ row.mps_no }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="mps_date" label="單據時間" width="180" />
      <el-table-column prop="fa_no_name" label="廠別" width="180" />
      <el-table-column prop="bo_no" label="產品料號" width="180" />
      <el-table-column prop="bo_no_name" label="品名" width="180" />
      <el-table-column prop="bo_no_spec" label="規格" width="180" />
      <el-table-column prop="mps_ym" label="年月" width="100" />
      <el-table-column prop="mps_qty" label="數量" width="100" />
    </el-table>

    <!-- 分頁 -->
    <el-pagination
      v-if="mpsList.length"
      background
      :current-page="page"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total"
      @current-change="handlePageChange"
    />

    <!-- 詳情對話方塊 -->
    <el-dialog :visible.sync="showDetails" width="80%">
      <template #header>
        <h3>主生產計劃詳情</h3>
      </template>
      <MPS002HDetail :mps_no="selectedMpsNo" />
    </el-dialog>
  </div>
</template>

b. 修改指令碼部分

setup 函式中,新增 filters 資料,並修改 fetchMpsList 函式以包含查詢引數。

<script>
import { ref, onMounted } from 'vue';
import { getMPS002 } from '@/api/mpsApp/MPS002HModel';
import MPS002HDetail from './MPS002HDetail.vue';

export default {
  components: { MPS002HDetail },
  setup() {
    const mpsList = ref([]);
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const loading = ref(false);
    const showDetails = ref(false);
    const selectedMpsNo = ref(null);

    const filters = ref({
      bo_no: '',
      item_name: '',
      item_spec: '',
      mps_ym: '',
    });

    const fetchMpsList = async () => {
      loading.value = true;
      try {
        const params = {
          page: page.value,
          page_size: pageSize.value,
          bo_no: filters.value.bo_no,
          item_name: filters.value.item_name,
          item_spec: filters.value.item_spec,
          mps_ym: filters.value.mps_ym,
        };
        const response = await getMPS002(params);
        mpsList.value = response.data.results;
        total.value = response.data.count;
      } catch (error) {
        console.error('Error fetching MPS002 list:', error);
      } finally {
        loading.value = false;
      }
    };

    const resetFilters = () => {
      filters.value = {
        bo_no: '',
        item_name: '',
        item_spec: '',
        mps_ym: '',
      };
      fetchMpsList();
    };

    const showMpsDetails = (mps_no) => {
      selectedMpsNo.value = mps_no;
      showDetails.value = true;
    };

    const handlePageChange = (newPage) => {
      page.value = newPage;
      fetchMpsList();
    };

    onMounted(fetchMpsList);

    return {
      mpsList,
      page,
      pageSize,
      total,
      loading,
      showDetails,
      selectedMpsNo,
      filters,
      fetchMpsList,
      resetFilters,
      showMpsDetails,
      handlePageChange,
    };
  },
};
</script>

2. 修改 MPS002D1List.vue(物料需求明細列表)

a. 新增查詢表單

<template>
  <div>
    <!-- 查詢表單 -->
    <el-form :inline="true" :model="filters" class="demo-form-inline">
      <el-form-item label="料號">
        <el-input v-model="filters.item_no" placeholder="請輸入料號"></el-input>
      </el-form-item>
      <el-form-item label="品名">
        <el-input v-model="filters.item_name" placeholder="請輸入品名"></el-input>
      </el-form-item>
      <el-form-item label="規格">
        <el-input v-model="filters.item_spec" placeholder="請輸入規格"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchMpsD1List">查詢</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 物料需求明細列表 -->
    <el-table :data="mpsD1List" style="width: 100%" v-loading="loading">
      <el-table-column prop="item_no" label="料號" width="180" />
      <el-table-column prop="item_name" label="品名" width="180" />
      <el-table-column prop="item_spec" label="規格" width="180" />
      <el-table-column prop="item_qty" label="需求數量" width="180" />
      <!-- 新增更多列 -->
    </el-table>

    <!-- 分頁 -->
    <el-pagination
      v-if="mpsD1List.length"
      background
      :current-page="page"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total"
      @current-change="handlePageChange"
    />
  </div>
</template>

b. 修改指令碼部分

<script>
import { ref, onMounted } from 'vue';
import { getMPS002D1 } from '@/api/mpsApp/MPS002D1Model';

export default {
  setup() {
    const mpsD1List = ref([]);
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const loading = ref(false);

    const filters = ref({
      item_no: '',
      item_name: '',
      item_spec: '',
    });

    const fetchMpsD1List = async () => {
      loading.value = true;
      try {
        const params = {
          page: page.value,
          page_size: pageSize.value,
          item_no: filters.value.item_no,
          item_name: filters.value.item_name,
          item_spec: filters.value.item_spec,
        };
        const response = await getMPS002D1(params);
        mpsD1List.value = response.data.results;
        total.value = response.data.count;
      } catch (error) {
        console.error('Error fetching MPS002D1 list:', error);
      } finally {
        loading.value = false;
      }
    };

    const resetFilters = () => {
      filters.value = {
        item_no: '',
        item_name: '',
        item_spec: '',
      };
      fetchMpsD1List();
    };

    const handlePageChange = (newPage) => {
      page.value = newPage;
      fetchMpsD1List();
    };

    onMounted(fetchMpsD1List);

    return {
      mpsD1List,
      page,
      pageSize,
      total,
      loading,
      filters,
      fetchMpsD1List,
      resetFilters,
      handlePageChange,
    };
  },
};
</script>

後端部分(Django REST Framework)

為了支援前端的查詢功能,需要在後端的檢視中新增篩選功能。

1. 修改 MPS002HModel 的檢視

from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from .models import MPS002HModel
from .serializers import MPS002HSerializer

class MPS002HViewSet(viewsets.ModelViewSet):
    queryset = MPS002HModel.objects.all().order_by('-mps_date')
    serializer_class = MPS002HSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['mps_ym']
    search_fields = ['bo_no__item_no', 'bo_no__item_name', 'bo_no__item_spec']

說明

  • filter_backends:使用 DjangoFilterBackendSearchFilter,可以實現精確過濾和模糊搜尋。
  • filterset_fields:精確過濾的欄位,這裡包括 mps_ym
  • search_fields:模糊搜尋的欄位,包括關聯的 bo_no(產品料號)的 item_noitem_nameitem_spec

2. 修改 MPS002D1Model 的檢視

from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from .models import MPS002D1Model
from .serializers import MPS002D1Serializer

class MPS002D1ViewSet(viewsets.ModelViewSet):
    queryset = MPS002D1Model.objects.all()
    serializer_class = MPS002D1Serializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    search_fields = ['item_no__item_no', 'item_no__item_name', 'item_no__item_spec']

說明

  • search_fields:對於物料需求明細,可以根據 item_no(料號)、item_name(品名)、item_spec(規格)進行模糊搜尋。

3. 安裝和配置 django-filter

如果還沒有安裝 django-filter,需要先安裝:

pip install django-filter

並在 settings.py 中新增:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

更新序列化器

確保您的序列化器包含必要的欄位,以便前端能夠正確接收資料。

MPS002HSerializer

from rest_framework import serializers
from .models import MPS002HModel

class MPS002HSerializer(serializers.ModelSerializer):
    fa_no_name = serializers.CharField(source='fa_no.fa_name', read_only=True)
    bo_no_name = serializers.CharField(source='bo_no.item_name', read_only=True)
    bo_no_spec = serializers.CharField(source='bo_no.item_spec', read_only=True)
    bo_no = serializers.CharField(source='bo_no.item_no', read_only=True)

    class Meta:
        model = MPS002HModel
        fields = ['id', 'mps_no', 'mps_date', 'fa_no', 'fa_no_name', 'bo_no', 'bo_no_name', 'bo_no_spec', 'mps_ym', 'mps_qty']

MPS002D1Serializer

from rest_framework import serializers
from .models import MPS002D1Model

class MPS002D1Serializer(serializers.ModelSerializer):
    item_name = serializers.CharField(source='item_no.item_name', read_only=True)
    item_spec = serializers.CharField(source='item_no.item_spec', read_only=True)
    item_no = serializers.CharField(source='item_no.item_no', read_only=True)

    class Meta:
        model = MPS002D1Model
        fields = ['id', 'mps_no', 'item_no', 'item_name', 'item_spec', 'item_qty', 'rmk']

更新 API 請求

1. 更新前端 API 呼叫

在您的 API 請求檔案中,確保查詢引數能夠正確傳遞。

MPS002HModel API

import request from '@/utils/request';
const baseUrl = '/mpsApp/MPS002HModel/';

export function getMPS002(params) {
  return request({
    url: baseUrl,
    method: 'get',
    params,
  });
}

MPS002D1Model API

import request from '@/utils/request';
const baseUrl = '/mpsApp/MPS002D1Model/';

export function getMPS002D1(params) {
  return request({
    url: baseUrl,
    method: 'get',
    params,
  });
}

總結

透過上述步驟,我們實現了:

  • 前端:在 MPS002HModelMPS002D1Model 的列表頁面中新增了查詢表單,可以根據指定的欄位進行篩選,並將查詢條件傳遞給後端。

  • 後端:在 Django REST Framework 的檢視中,使用 django-filterSearchFilter 實現了對指定欄位的精確過濾和模糊搜尋。

  • 序列化器:更新了序列化器,以便在返回資料時包含關聯欄位的資訊,如品名和規格。

  • API 請求:確保查詢引數能夠正確地透過前端 API 請求傳送到後端。

這樣,使用者就可以在前端介面上根據產品料號、品名、規格和年月對主生產計劃列表進行查詢,也可以在物料需求明細列表中根據料號、品名、規格進行篩選。

相關文章