<script setup> import { ref, watch, onMounted } from "vue"; import BaseInput from…
- User
<div class="search-switch"> <v-switch v-model="advancedSearchOn" label="Расширенный поиск" color="primary-blue" /> </div> <div v-if="advancedSearchOn" class="advanced-search-box"> <v-window v-model="currentSearchWindow" show-arrows :continuous="true" style="width: 1000px;" > <template v-slot:prev="{ props }"> <button @click="props.onClick" class="arrow-button prev-arrow"> <v-icon size="36" color="primary">mdi-chevron-left</v-icon> </button> </template> <template v-slot:next="{ props }"> <button @click="props.onClick" class="arrow-button next-arrow"> <v-icon size="36" color="primary">mdi-chevron-right</v-icon> </button> </template> <v-window-item v-for="(item, index) in typesOfSearch" :key="Object.keys(item)[0]" :value="Object.keys(item)[0]" > <v-card class="d-flex justify-center"> <div class="search-window"> <p class="d-block ml-10 mt-2 fs-18 fw-regular color-primary-blue"> {{ Object.values(item)[0] }} </p> <div class="pl-10 pr-10 pt-3"> <v-divider /> </div> <template v-if="metadata[Object.keys(item)[0]]"> <div v-for="(row, rowIndex) in metadata[Object.keys(item)[0]]" :key="rowIndex" class="d-flex justify-space-between mt-5" > <template v-for="(field, fieldIndex) in row" :key="field.name"> <!-- Date inputs --> <template v-if="field.type === 'date'"> <div class="d-flex justify-space-between pl-10 pr-10" style="height: 30px;"> <div class="d-flex justify-space-between"> <date-input placeholder="Дата от" teleport="#datepicker-container" v-model="dateRangeFrom" style="width: 155px; margin-right: 13px" /> <date-input placeholder="Дата до" teleport="#datepicker-container" :min-date="stringToDate(dateRangeFrom)" v-model="dateRangeTo" style="width: 155px; margin-left: 13px" /> </div> </div> </template> <!-- Regular text inputs --> <base-input v-else v-model="formData[field.name]" :placeholder="field.placeholder" class="base-input-size" :class="{ 'ml-10': fieldIndex === 0, 'mr-10': fieldIndex === row.length - 1 }" /> </template> </div> </template> </div> </v-card> </v-window-item> </v-window> </div> <router-view :key="route.fullPath" /> </div> - Assistant
Sure! I'll help you modify your Vue.js component so that the common search form uses keys for the fields, similar to the advanced search forms. Here's the complete modified code with detailed explanations:
Modified Vue Component
<script setup> import { ref, watch, onMounted } from "vue"; import BaseInput from "@/components/common/BaseInput.vue"; import DateInput from "@/components/common/DateInput.vue"; import { useRoute, useRouter } from "vue-router"; import { getOptions } from "@/api/default_api_promises"; // Initialize router and route const route = useRoute(); const router = useRouter(); // Reactive state variables const advancedSearchOn = ref(false); const formData = ref({}); const metadata = ref({}); const dateRangeFrom = ref(null); const dateRangeTo = ref(null); // Define search window types const typesOfSearch = [ { common: "Общий поиск" }, { image: "Поиск фотодокументов" }, { audio: "Поиск фонодокументов" }, { video: "Поиск киновидеодокументов" } ]; const currentSearchWindow = ref("common"); // Function to load metadata for search forms async function loadMetadata() { try { // Define common search fields const commonFields = { title: { label: "Название" }, description: { label: "Описание" }, date: { label: "Дата", type: "date" }, archive_number: { label: "Архивный номер" }, authors: { label: "Авторы" }, personalities: { label: "Персоналии" } }; metadata.value.common = formatFields(commonFields); console.log('Common fields initialized:', metadata.value.common); // Load metadata for other material types for (const type of ['image', 'audio', 'video']) { const { data } = await getOptions({ url: `/api/${type}-materials/` })(); metadata.value[type] = formatFields(data.actions.list); console.log(`${type} fields loaded:`, metadata.value[type]); } } catch (error) { console.error('Error loading metadata:', error); } } // Helper function to format fields into rows function formatFields(listData) { const entries = Object.entries(listData) .filter(([key]) => key !== 'id') // Exclude 'id' field .map(([key, value]) => ({ name: key, placeholder: value.label, type: value.type || 'text' })); // Group fields into rows of two const rows = []; for (let i = 0; i < entries.length; i += 2) { rows.push(entries.slice(i, Math.min(i + 2, entries.length))); } return rows; } // Handle form submission function handleSubmit() { const minInputLength = 3; if (advancedSearchOn.value) { handleAdvancedSearch(); } else { // Check if any common search field meets the minimum length const hasValidInput = Object.values(formData.value).some(value => value && value.toString().length >= minInputLength ); if (hasValidInput) { handleCommonSearch(); } } } // Handle common search submission function handleCommonSearch() { const query = { page: 1, page_size: 5, material_type: 'common' }; // Add formData fields relevant to common search if (metadata.value.common) { metadata.value.common.forEach(row => { row.forEach(field => { const value = formData.value[field.name]; if (value) { if (field.type === 'date') { // Handle date input if necessary // For simplicity, using single date field; adjust as needed query[`${field.name}__icontains`] = value; } else { query[`${field.name}__icontains`] = value; } } }); }); } // Add date range if present if (dateRangeFrom.value) { query.date_from = dateRangeFrom.value; } if (dateRangeTo.value) { query.date_to = dateRangeTo.value; } // Navigate to search results with query parameters router.push({ name: "search", query }); } // Handle advanced search submission function handleAdvancedSearch() { const query = { page: 1, page_size: 5, material_type: currentSearchWindow.value, }; // Add all filled formData fields for (const [key, value] of Object.entries(formData.value)) { if (value) { query[`${key}__icontains`] = value; } } // Add date range if present if (dateRangeFrom.value) { query.date_from = dateRangeFrom.value; } if (dateRangeTo.value) { query.date_to = dateRangeTo.value; } // Navigate to search results with query parameters router.push({ name: "search", query }); } // Utility function to convert string to Date object function stringToDate(dateString) { if (dateString) { const [day, month, year] = dateString.split('.'); return new Date(year, month - 1, day); } return null; } // Scroll the window to a specific position smoothly function scrollToOneThirdHeight() { const height = window.innerHeight; window.scrollTo({ top: height / 2, behavior: 'smooth' }); } // Watcher to handle scrolling when advanced search is toggled watch(advancedSearchOn, (newVal) => { if (newVal) { scrollToOneThirdHeight(); } }); // Watcher to clear form data when switching search types watch(currentSearchWindow, () => { formData.value = {}; dateRangeFrom.value = null; dateRangeTo.value = null; }); // Initialize component on mount onMounted(() => { loadMetadata(); // Populate formData from URL query parameters if present if (route.query) { Object.entries(route.query).forEach(([key, value]) => { if (key.includes('__icontains')) { const fieldName = key.replace('__icontains', ''); formData.value[fieldName] = value; } else if (key === 'date_from') { dateRangeFrom.value = value; } else if (key === 'date_to') { dateRangeTo.value = value; } }); } }); </script> <template> <div class="home"> <!-- Container for datepicker teleportation --> <div id="datepicker-container" /> <div class="wrapper wrapper__indent"> <!-- Common Search Form --> <div class="search-box"> <div v-if="metadata.common" class="common-search-fields"> <div v-for="(row, rowIndex) in metadata.common" :key="rowIndex" class="d-flex space-x-2" > <div v-for="field in row" :key="field.name" class="field-container" > <!-- Date Inputs --> <template v-if="field.type === 'date'"> <date-input placeholder="Дата от" teleport="#datepicker-container" v-model="dateRangeFrom" class="date-input" /> <date-input placeholder="Дата до" teleport="#datepicker-container" :min-date="stringToDate(dateRangeFrom)" v-model="dateRangeTo" class="date-input" /> </template> <!-- Regular Text Inputs --> <template v-else> <base-input @keyup.enter="handleSubmit" v-model="formData[field.name]" :placeholder="field.placeholder" class="base-input-size" /> </template> </div> </div> </div> <!-- Search Button --> <v-btn @click="handleSubmit" variant="outlined" class="search-button"> <v-icon size="28" class="search-icon" color="primary">mdi-magnify</v-icon> </v-btn> </div> <!-- Toggle for Advanced Search --> <div class="search-switch"> <v-switch v-model="advancedSearchOn" label="Расширенный поиск" color="primary-blue" /> </div> <!-- Advanced Search Form --> <div v-if="advancedSearchOn" class="advanced-search-box"> <v-window v-model="currentSearchWindow" show-arrows :continuous="true" style="width: 1000px;" > <!-- Previous Arrow --> <template v-slot:prev="{ props }"> <button @click="props.onClick" class="arrow-button prev-arrow"> <v-icon size="36" color="primary">mdi-chevron-left</v-icon> </button> </template> <!-- Next Arrow --> <template v-slot:next="{ props }"> <button @click="props.onClick" class="arrow-button next-arrow"> <v-icon size="36" color="primary">mdi-chevron-right</v-icon> </button> </template> <!-- Search Window Items --> <v-window-item v-for="(item, index) in typesOfSearch" :key="Object.keys(item)[0]" :value="Object.keys(item)[0]" > <v-card class="d-flex justify-center"> <div class="search-window"> <p class="d-block ml-10 mt-2 fs-18 fw-regular color-primary-blue"> {{ Object.values(item)[0] }} </p> <div class="pl-10 pr-10 pt-3"> <v-divider /> </div> <!-- Advanced Search Fields --> <template v-if="metadata[Object.keys(item)[0]]"> <div v-for="(row, rowIndex) in metadata[Object.keys(item)[0]]" :key="rowIndex" class="d-flex justify-space-between mt-5" > <template v-for="(field, fieldIndex) in row" :key="field.name"> <!-- Date Inputs --> <template v-if="field.type === 'date'"> <div class="d-flex justify-space-between pl-10 pr-10" style="height: 30px;"> <div class="d-flex justify-space-between"> <date-input placeholder="Дата от" teleport="#datepicker-container" v-model="dateRangeFrom" style="width: 155px; margin-right: 13px" /> <date-input placeholder="Дата до" teleport="#datepicker-container" :min-date="stringToDate(dateRangeFrom)" v-model="dateRangeTo" style="width: 155px; margin-left: 13px" /> </div> </div> </template> <!-- Regular Text Inputs --> <base-input v-else v-model="formData[field.name]" :placeholder="field.placeholder" class="base-input-size" :class="{ 'ml-10': fieldIndex === 0, 'mr-10': fieldIndex === row.length - 1 }" /> </template> </div> </template> </div> </v-card> </v-window-item> </v-window> </div> <!-- Router View for Search Results --> <router-view :key="route.fullPath" /> </div> </div> </template> <style lang="scss" scoped> .search-box { display: flex; align-items: center; position: relative; } .common-search-fields { display: flex; flex-wrap: wrap; gap: 10px; } .field-container { display: flex; flex-direction: column; } .base-input-size { width: 300px !important; height: 40px !important; padding: 10px; } .date-input { width: 150px !important; margin-bottom: 10px; } .search-button { height: 60px; width: 60px; border: solid 1px darkgray; margin-left: 10px; display: flex; align-items: center; justify-content: center; } .search-icon { height: 28px; width: 28px; } .search-switch { display: flex; justify-content: left; margin-left: 20px; margin-top: 20px; } .advanced-search-box { display: flex; justify-content: center; margin-top: 20px; } .search-window { width: 800px; padding: 15px; } .arrow-button { position: absolute; top: 50%; transform: translateY(-50%); opacity: 0; transition: opacity 0.4s ease; border: none; background: transparent; cursor: pointer; } .arrow-button.prev-arrow { left: 10px; } .arrow-button.next-arrow { right: 10px; } .advanced-search-box:hover .arrow-button { opacity: 1; } .item { width: 900px; padding: 15px; margin-top: 15px; margin-bottom: 15px; border: 1px solid darkgray; border-radius: 8px; display: flex; justify-content: left; } .item-label { display: block; font-size: 12px; } </style>Explanation of Changes
-
Removed
commonSearchInput:- The original
commonSearchInputwas a single input field for the common search. This has been removed to allow multiple fields based on keys, similar to the advanced search.
- The original
-
Utilized
formDatafor Common Search:- Instead of having a separate
commonSearchInput, we now useformDatato store all input values, including those from the common search form. This ensures consistency across both common and advanced search forms.
- Instead of having a separate
-
Dynamic Rendering of Common Search Fields:
- In the
<template>, the common search fields are dynamically rendered based onmetadata.common. This allows flexibility in adding or removing fields without changing the template structure.
- In the
-
Adjusted
handleSubmit:- The
handleSubmitfunction now checks if any of the common search fields meet the minimum input length requirement before proceeding with the search. It determines whether to perform a common or advanced search based on the toggle.
- The
-
Updated
handleCommonSearch:- This function now iterates through the
metadata.commonfields and constructs the query parameters based on the filled fields informData. It ensures that all relevant fields are included in the search query.
- This function now iterates through the
-
Enhanced Layout and Styling:
- The CSS has been updated to accommodate multiple input fields in the common search form. Classes like
.common-search-fieldsand.field-containerhelp in organizing the layout.
- The CSS has been updated to accommodate multiple input fields in the common search form. Classes like
-
Date Range Handling:
- Date inputs are handled similarly in both common and advanced searches, allowing users to specify a date range for their search queries.
-
Initialization from Route Query:
- On component mount, the form initializes
formDatawith any existing query parameters from the URL, ensuring that search state is preserved across navigation.
- On component mount, the form initializes
Usage
With these modifications, the common search form now dynamically uses field keys defined in the
metadata.commonobject. This approach provides a more scalable and maintainable structure, especially when dealing with multiple fields. It also ensures consistency between common and advanced search functionalities within the component.Feel free to adjust the
commonFieldsobject in theloadMetadatafunction to add or remove fields as needed. The dynamic rendering in the template will automatically adapt to these changes. -