Mac端提交表单时生成JSON文件的技术实现咨询
可以用Axios和Vuelidate实现你的所有需求
以下是完整的实现方案,基于你提供的Vue 3代码改造:
1. 安装所需依赖
在项目根目录执行命令:
npm install axios @vuelidate/core @vuelidate/validators # 或使用yarn yarn add axios @vuelidate/core @vuelidate/validators
2. 完整组件代码实现
<template> <div> <form @submit.prevent="handleSubmit"> <div> <label for="order-id">订单ID</label> <input v-model="form.orderId" id="order-id" type="text" placeholder="1547089" /> <!-- 显示订单ID校验错误 --> <span v-if="v$.orderId.$error" style="color: red;"> {{ v$.orderId.$errors[0].$message }} </span> </div> <div> <label for="password">验证密码</label> <input v-model="form.password" type="password" placeholder="****" /> <!-- 显示密码校验错误 --> <span v-if="v$.password.$error" style="color: red;"> {{ v$.password.$errors[0].$message }} </span> </div> <div id="div-submit"> <button :disabled="!v$.valid" id="submit" type="submit" >提交</button> </div> </form> </div> </template> <script setup> import { reactive } from 'vue' import { useVuelidate } from '@vuelidate/core' import { required, minLength, maxLength } from '@vuelidate/validators' import axios from 'axios' // 表单数据绑定 const form = reactive({ orderId: '', password: '' }) // Vuelidate校验规则配置 const rules = { orderId: { required: required('订单ID不能为空'), minLength: minLength(1, '订单ID不可为空') }, password: { required: required('密码不能为空'), minLength: minLength(4, '密码必须是4位'), maxLength: maxLength(4, '密码必须是4位') } } const v$ = useVuelidate(rules, form) // 提交处理逻辑 const handleSubmit = async () => { // 触发全量校验 const isValid = await v$.validate() if (!isValid) return try { // 1. 发送有效数据到同事的服务器 await axios.post('https://同事的服务器接口地址', form) // 2. 在Mac本地保存JSON文件 const jsonContent = JSON.stringify(form, null, 2) const blob = new Blob([jsonContent], { type: 'application/json' }) const downloadUrl = URL.createObjectURL(blob) const link = document.createElement('a') link.href = downloadUrl link.download = `表单数据_${Date.now()}.json` document.body.appendChild(link) link.click() document.body.removeChild(link) URL.revokeObjectURL(downloadUrl) // 3. 弹出完成提示 alert('DONE') } catch (error) { console.error('提交失败:', error) alert('提交出错,请重试') } } </script>
关键功能说明
- 表单校验:通过Vuelidate定义字段规则,实时反馈错误,提交前强制校验所有字段,确保只有有效数据进入后续流程。
- 数据发送:使用Axios发送POST请求,替换代码中
https://同事的服务器接口地址为实际接口即可。 - 本地JSON保存:通过Blob生成JSON文件,利用a标签触发下载,Mac系统默认保存到「下载」文件夹。
- 完成提示:所有操作成功后弹出
DONE提示窗口。
内容的提问来源于stack exchange,提问作者Roman Šnĕrer
相关产品推荐
相关产品推荐

