请求完成后使用vue-json-excel下载JSON数据的技术咨询
Got it, let's adjust your setup so you can first fetch your routes data via API, then trigger the Excel download only after the request succeeds. Here's a straightforward approach:
Step 1: Restructure Your Template
Instead of tying the download trigger directly to the json-excel component, we'll use a separate button to handle the click, and hide the json-excel component (we'll trigger it programmatically later). Add a ref to the component so we can access its methods:
<div class="column is-narrow"> <!-- Your visible download button --> <button class="button is-primary" @click="btDispatch"> <span class="icon"><i class="fa fa-download"></i></span> <span>Descargar entregas</span> </button> <!-- Hidden excel component, controlled via ref --> <json-excel ref="excelDownload" style="display: none" :data="routes" :fields="json_fields_routes" :name="`descarga-rutas.xls`" ></json-excel> </div>
Step 2: Update Your Method to Fetch Data First
Modify your btDispatch method to first make your API request, wait for the data to load, then trigger the download using the json-excel component's internal generate() method:
export default { data() { return { routes: [], json_fields_routes: { // Keep your existing field configuration here } }; }, methods: { async btDispatch() { try { // 1. Fetch your data from the API first const apiResponse = await this.$axios.get('/your-api-endpoint'); // Replace with your actual API URL this.routes = apiResponse.data; // Assign the fetched data to your routes variable // 2. Once data is ready, trigger the Excel download this.$refs.excelDownload.generate(); } catch (error) { // Handle any errors (e.g., network issues, invalid response) console.error('Failed to fetch data:', error); // Optionally show a user-friendly error message here // this.$notify.error('No se pudo obtener los datos para descargar'); } } } };
Key Explanations:
- We moved the click handler to a regular button so we can control the flow: first request, then download.
- The
ref="excelDownload"gives us access to thejson-excelcomponent instance, letting us call itsgenerate()method directly when we're ready. - Using
async/awaitensures we wait for the API request to finish before trying to download (you can also use.then()if you prefer promise chaining). - We added error handling to catch issues with the API request, so you can inform the user if something goes wrong.
Note:
Make sure your API request returns the correct JSON structure that matches your json_fields_routes configuration—this ensures the Excel file is generated properly once the data is loaded.
内容的提问来源于stack exchange,提问作者Piero Pajares

