詳解Vue返回值動態(tài)生成表單及提交數(shù)據(jù)的辦法
更新時間:2021年12月27日 10:13:34 作者:mqy1023
這篇文章主要為大家介紹了Vue返回值動態(tài)生成表單及提交數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
主要解決的問題
1、vue在循環(huán)的時候需要動態(tài)綁定不同的v-model;vue動態(tài)的表單,數(shù)據(jù)怎么綁定呢?
2、動態(tài)表單上所有name屬性對應的鍵值對的形式提交到后端
一、后端返回的數(shù)據(jù),提交到后端的數(shù)據(jù)格式如下:
// 后端返回的數(shù)據(jù),根據(jù)返回類型用對應的組件
[
{
"componentType": "input",
"componentName": "username",
"required": "1", // 提交時是否要必須填寫
"name": "姓名",
},
{
"componentType": "radio",
"componentName": "sex",
"required": "1",
"name": "性別",
"options": [
{
"name": "男",
"value": "0000"
},
{
"name": "女",
"value": "1111"
}
]
}
]
// 提交到服務器的數(shù)據(jù)格式
{
username: '我的姓名',
sex: '0000' // 對應”男“
}
二、vue前端代碼如下:
<template>
<div class="page-container">
<div class="dynamic-content">
<div v-for="(item,idx) in infoList" :key="idx">
<input class="common-input" v-model="modelItems[idx]" v-if="item.componentType=='input'">
<van-radio-group v-model="modelItems[idx]" direction="horizontal" v-if="item.componentType=='radio'">
<van-radio :name="itemRadio.value" v-for="itemRadio in item.options" :key="itemRadio.value">
{{itemRadio.name}}
</van-radio>
</van-radio-group>
</div>
<div class="common-btn" @click="clickSubmit">提交數(shù)據(jù)</div>
</div>
</div>
</template>
<script>
import Vue from 'vue'
import { getListData } from '@/api/home'
import { RadioGroup, Radio } from 'vant'
Vue.use(Radio).use(RadioGroup)
export default {
data() {
return {
modelItems: {}, // vue在循環(huán)的時候需要動態(tài)綁定不同的v-model
infoList: []
}
},
mounted() {
this.formKeyArr = []
this.getList()
},
methods: {
getList() {
getListData()
.then((res) => {
const infoListData = res.infoList
this.infoList = infoListData
infoListData.forEach((item, index) => {
// 保存屬性name和是否必填,后續(xù)提交數(shù)據(jù)用到
// { name: 'username', type: 1 }, { name: 'sex', type: 1}
this.formKeyArr.push({ name: item.componentName, type: item.required })
})
})
.catch(() => {
})
},
clickSubmit() {
const postParams = {} // 提交的數(shù)據(jù)
let isCanSubmit = true
this.formKeyArr.forEach((item, index) => {
console.log('item=', item)
if (item.type === '1' && !this.modelItems[index]) { // 所有require必須的標記符
// 請先填寫完成, toast請?zhí)顚懲暾?
isCanSubmit = false
}
postParams[item['name']] = this.modelItems[index]
})
if (isCanSubmit) {
// 可以提交數(shù)據(jù)
// 可以拿到提交表單數(shù)據(jù)
// { username: '我的姓名', sex: '0000' // 對應”男“ }
console.log('postParams=', postParams)
}
}
}
}
</script>
<style lang="scss">
</style>
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
vue keep-alive 動態(tài)刪除組件緩存的例子
今天小編就為大家分享一篇vue keep-alive 動態(tài)刪除組件緩存的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

