Detailed explanation of how Vue returns values ​​to dynamically generate forms and submit data

Detailed explanation of how Vue returns values ​​to dynamically generate forms and submit data

Main issues solved

1. Vue needs to dynamically bind different v-models when looping; how to bind data to Vue's dynamic form?

2. All key-value pairs corresponding to the name attributes on the dynamic form are submitted to the backend

1. The data returned by the backend and submitted to the backend are in the following format:

// The data returned by the backend is used with the corresponding component according to the return type [
	{
	    "componentType": "input",
	    "componentName": "username",
	    "required": "1", // Whether it is required to fill in when submitting "name": "Name",
	},
	{
        "componentType": "radio",
        "componentName": "sex",
        "required": "1",
        "name": "Gender",
        "options": [
            {
                "name": "Male",
                "value": "0000"
            },
            {
                "name": "Female",
                "value": "1111"
            }
        ]
   }
]
// Data format submitted to the server {
	username: 'My name',
	sex: '0000' // corresponds to "male"
}

2. The vue front-end code is as follows:

<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">Submit data</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 needs to dynamically bind different v-models when looping
      infoList: []
    }
  },
  mounted() {
    this.formKeyArr = []
    this.getList()
  },
  methods: {
    getList() {
      getListData()
        .then((res) => {
          const infoListData = res.infoList
          this.infoList = infoListData
          infoListData.forEach((item, index) => {
          	// Save the attribute name and whether it is required, which will be used for subsequent data submission // { name: 'username', type: 1 }, { name: 'sex', type: 1}
            this.formKeyArr.push({ name: item.componentName, type: item.required })
          })
        })
        .catch(() => {
        })
    },
    clickSubmit() {
      const postParams = {} // Submitted data let isCanSubmit = true
      this.formKeyArr.forEach((item, index) => {
        console.log('item=', item)
        if (item.type === '1' && !this.modelItems[index]) { // All require tags // Please fill in the form first, please fill in the toast form completely isCanSubmit = false
        }
        postParams[item['name']] = this.modelItems[index]
      })
      if (isCanSubmit) {
      	//Can submit data //Can get the submitted form data //{ username: 'my name', sex: '0000' //corresponds to "male" }
      	console.log('postParams=', postParams)
      }
    }
  }
}
</script>
<style lang="scss">
</style>

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Vue implements converting form data into json format
  • Vue form data interactive submission demonstration tutorial
  • vue adds and edits using the same form, el-form clears form data after form submission
  • How to get form data in Vue
  • Vue implements the function of adding, deleting and modifying form data
  • How to use Element-ui form in Vue to send data and multiple pictures to the backend
  • Details of Vue's method for collecting form data

<<:  Dynamically add tables in HTML_PowerNode Java Academy

>>:  How to quickly query 10 million records in Mysql

Recommend

The use of MySQL triggers and what to pay attention to

Table of contents About Triggers Use of triggers ...

MySQL Optimization: InnoDB Optimization

Study plans are easily interrupted and difficult ...

Full analysis of web page elements

Relative Length Units em Description: Relative len...

Detailed explanation of two quick ways to write console.log in vscode

(I) Method 1: Define it in advance directly in th...

Comprehensive summary of mysql functions

Table of contents 1. Commonly used string functio...

How to manage cached pages in Vue

Table of contents Problem 1: Destruction 1. How t...

A solution to the abnormal exit of Tomcat caused by semaphore

I'm playing with big data recently. A friend ...

onfocus="this.blur()" is hated by blind webmasters

When talking about the screen reading software op...

MySQL string splitting operation (string interception containing separators)

String extraction without delimiters Question Req...

Example of using CSS3 to create Pikachu animated wallpaper

text OK, next it’s time to show the renderings. O...

Implementation of vue-nuxt login authentication

Table of contents introduce Link start Continue t...

Summary of 11 common mistakes made by MySQL call novices

Preface You may often receive warning emails from...

Remote development with VSCode and SSH

0. Why do we need remote development? When develo...

Sample code for implementing the Olympic rings with pure HTML+CSS

Rendering Code - Take the blue and yellow rings a...

Detailed explanation of how to configure static IP in Centos8

After installing centos 8, the following error wi...