vben amin 的 FormSchema 中 component 可以直接用一個 API 取值回來,不用自己先在外面用一個 fuction 整理好 options
不過 vben admin 的文檔並沒有好好的寫這個部分,非常可惜。

{
      field: 'api_select_sample_id',
      component: 'ApiSelect',
      label: '下拉選單範例',
      componentProps: {
        api:SelectList, // Assuming this is the function to call the API
        params: { items: 1000 },
        placeholder: '下拉選單範例',
        resultField: 'list',
        labelField: 'name',
        valueField: 'id',
        showSearch: true,
        filterOption: (input, option) => (option?.label ?? '').includes(input),
        onSearch: (value) => {
          console.log('onSearch', value);
        },
        onChange: (e) => {
          console.log('onChange',e);
        },
      },
    },

上面就是一個範例,針對每個參數我們進行一下說明

  • field :欄位的 key 值
  • component :選用 ApiSelect 這個組件
  • label :欄位顯示的標題
  • api :api 要呼叫的 function
  • params : api 要搭配送出給 function 的參數
  • resultField :這個很重要,如果你的 API 不是回傳的根目錄就是清單的你就要設定要從哪邊開始解析,通常我的 API 都是放在 list 下才開始
  • labelField :設定要放進去到 label 的欄位節點
  • valueField :設定要放到 value 的節點
  • showSearch:開啟即時搜尋篩選功能
  • filterOption : 設定將 label 設定成搜尋的內容而不是用 value

加上這堆東西後,你的下拉選單可以直接串API 以外又同時可以即時輸入篩選

最後修改日期: 2024 年 2 月 20 日

作者