Vue3如何合并三个select标签的年月日数据并通过axios提交后端
Vue3 注册页出生日期拼接方案修复
问题核心
你当前的代码存在3个核心问题:
- 三个年月日select全部绑定到了同一个
info.birthDate字段,无法分别拿到年/月/日的选中值 - 缺少对月份、日期的补零逻辑,无法输出
YYYYMMDD格式的出生日期 - Vuex 中异步请求放在了mutation内,且提交的payload没有同步到state的Userinfo中
完整修复步骤
1. 修改 Join.vue 模板中select的绑定逻辑
把原来的三个select的v-model从统一绑定info.birthDate,改为按filter的name分别绑定,同时补充option的value属性:
<select v-for="filter in filters" v-model="info[filter.name]" :key="filter.name" class="form-select"> <option v-for="item in filter.items" :value="item" :key="item"> {{ item }} </option> </select>
2. 修改 Join.vue 的submitForm方法,新增出生日期拼接逻辑
在提交到Vuex之前,把年、月、日拼接成要求的8位格式,补零处理不足2位的月份和日期:
async submitForm() { // 拼接出生日期,补零处理 const year = this.info.year const month = String(this.info.month).padStart(2, '0') const day = String(this.info.day).padStart(2, '0') this.info.birthDate = `${year}${month}${day}` await this.$store.dispatch('signup/addUsers', this.info) alert('회원가입이 완료되었습니다. 새로운 환경에서 로그인 해주세요.') this.$store.commit('signup/resetRegistration') this.$router.push('/') }
3. 调整Vuex的join.js逻辑
首先在state的Userinfo中新增年、月、日三个临时存储字段,其次把axios请求移到action中(mutation不建议放异步逻辑),同步提交的payload到state:
import axios from 'axios' export default { namespaced: true, state: { Userinfo: { userId: '', password: '', passwordConfirm: '', userName: '', year: '', month: '', day: '', birthDate: '', phoneNumber: '', email: '' } }, getters: {}, mutations: { setUserInfo(state, payload) { // 把提交的用户数据同步到state state.Userinfo = { ...state.Userinfo, ...payload } }, resetRegistration(state) { state.Userinfo = { userId: '', password: '', passwordConfirm: '', userName: '', year: '', month: '', day: '', birthDate: '', phoneNumber: '', email: '' } } }, actions: { async addUsers({ commit, state }, payload) { // 先同步用户数据到state commit('setUserInfo', payload) try { // 异步请求放在action中 const response = await axios.post('http://你的接口地址/api/signup', state.Userinfo) console.log(response) } catch (error) { console.log(error) } } } }
效果验证
选择2015年5月16日时,会自动拼接为20150516存入birthDate字段,和其余字段一起提交到后端接口。
内容的提问来源于stack exchange,提问作者skwFE
相关产品推荐
相关产品推荐

