Element-UI 2.3.7日期选择器如何禁用数组内日期(异步场景)
Hey there! I've run into a similar scenario with Element UI's date picker before, so let me share how to handle this properly.
The key here is leveraging Vue's reactivity system — you don't need to wait for the API response to set up picker-options initially. Instead, you can initialize an empty array for your disabled dates, update it once the API returns data, and the disabledDate function will automatically use the latest values.
Here's a step-by-step solution tailored to your code:
- Initialize a reactive array for disabled dates in
data
Add an empty array to hold the dates you want to disable, right alongside your existingpickerOptions:
data() { return { valueDateTimeOrder: '', disabledDates: [], // Empty array to start with pickerOptions: { disabledDate: (time) => { // Keep your original logic to disable future dates const isFutureDate = time.getTime() > Date.now(); // Check if the current date is in our disabledDates array const isDisabled = this.disabledDates.some(disabledDate => { // Convert the disabled date from API to a Date object const targetDate = new Date(disabledDate); // Compare year, month, and day to ignore time differences return time.getFullYear() === targetDate.getFullYear() && time.getMonth() === targetDate.getMonth() && time.getDate() === targetDate.getDate(); }); // Disable the date if it's either future or in our disabled list return isFutureDate || isDisabled; } } }; }
- Fetch the disabled dates from your API and update the array
Create a method to call your API, then assign the returned dates tothis.disabledDates. Vue's reactivity will ensure thedisabledDatefunction picks up the new values immediately:
methods: { async getDisabledDates() { try { // Replace this with your actual API call const apiResponse = await axios.get('/your-api-endpoint'); // Assume the API returns an array of date strings (e.g., ["2024-05-10", "2024-05-15"]) this.disabledDates = apiResponse.data; } catch (error) { console.error('Error fetching disabled dates:', error); } } }
- Trigger the API call when the component mounts
Call your API method in themountedhook so the disabled dates are fetched as soon as the component initializes:
mounted() { this.getDisabledDates(); }
Why this works:
Element UI's date picker re-runs the disabledDate function every time the picker is opened or the month/year is changed. Since this.disabledDates is reactive, any updates to it will be reflected immediately in the function's logic — no need to reassign or reconfigure picker-options after the API call.
Quick note on date formatting:
Make sure the dates returned from your API are in a format that new Date() can parse correctly (like ISO strings "YYYY-MM-DD"). If your API returns dates in a different format, you might need to adjust the conversion logic inside the some() method to match.
内容的提问来源于stack exchange,提问作者Corey

