PluginConfigForm.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <el-card shadow="never" class="settings-card">
  3. <template #header>
  4. <div class="card-header">
  5. <slot name="header">
  6. <span>插件配置</span>
  7. </slot>
  8. </div>
  9. </template>
  10. <formCreate
  11. :rule="configRule"
  12. :option="configOptions"
  13. v-if="configRule.length > 0"
  14. />
  15. <el-empty v-else description="暂无配置项" />
  16. </el-card>
  17. </template>
  18. <script setup>
  19. import { ref, watch } from 'vue'
  20. import { ElMessage } from 'element-plus'
  21. import { getPluginConfigApi, savePluginConfigApi } from '@/api/plugin'
  22. import {useUserStore} from "@/store/user.js";
  23. import formCreate from '@form-create/element-ui'
  24. const userStore = useUserStore()
  25. const props = defineProps({
  26. pluginId: {
  27. type: String,
  28. required: true
  29. },
  30. setting: {
  31. type: String,
  32. default: null
  33. }
  34. })
  35. const configRule = ref([])
  36. const loading = ref(false)
  37. const configOptions = ref({
  38. form: {
  39. labelPosition: 'right',
  40. },
  41. submitBtn: {
  42. innerText: '保存配置',
  43. loading: loading
  44. },
  45. resetBtn: true,
  46. onSubmit: async (formData) => {
  47. try {
  48. loading.value = true
  49. await savePluginConfigApi(props.pluginId, formData)
  50. ElMessage.success('配置保存成功')
  51. } finally {
  52. loading.value = false
  53. }
  54. },
  55. beforeFetch: (options) => {
  56. options.headers = {
  57. Authorization: `Bearer ${userStore.token}`
  58. };
  59. }
  60. })
  61. const loadConfig = async () => {
  62. formCreate.setData('API_TOKEN', userStore.token)
  63. formCreate.setData('API_BASE_URL', import.meta.env.VITE_API_BASE_URL)
  64. try {
  65. let { data } = await getPluginConfigApi(props.pluginId)
  66. if (!Array.isArray(data)) {
  67. console.warn('Expected configRule to be an array, but got:', typeof data)
  68. data = []
  69. }
  70. if (props.setting) {
  71. const findSetting = (items, target) => {
  72. for (const item of items) {
  73. if (item.field === target) return item
  74. if (item.children) {
  75. const found = findSetting(item.children, target)
  76. if (found) return found
  77. }
  78. }
  79. return null
  80. }
  81. const setting = findSetting(data, props.setting)
  82. configRule.value = setting ? [setting] : []
  83. } else {
  84. configRule.value = data
  85. }
  86. } catch (e) {
  87. console.error('加载配置失败:', e)
  88. ElMessage.error('配置加载失败')
  89. }
  90. }
  91. // 监听参数变化自动加载
  92. watch(() => props.pluginId, loadConfig, { immediate: true })
  93. watch(() => props.setting, loadConfig)
  94. </script>
  95. <style scoped>
  96. .settings-card {
  97. margin-bottom: 20px;
  98. }
  99. </style>