Detailed application of Vue dynamic form

Detailed application of Vue dynamic form

Overview

There are many form requirements in the background management system. We hope to be able to write data in json format and dynamically render dynamic forms through the vue loop. And it is possible to obtain the rendered form data externally, so as to perform a warehousing operation.

Understanding v-model

vue-model is equivalent to passing a value to the form element and externally listening to input events. Therefore, when we encapsulate the form component ourselves, we can also pass a value and listen to the input event to obtain the input value.

<input type="text" v-model="thing">

<!-- Equivalent to -->
<input type="text" v-bind:value="thing" 
       v-on:input="thing = $event.target.value">

Business application scenarios

I was recently writing an online education platform and found that when adding courses in the background, the parameters required for each course were different (some courses had no special parameters). Using a fixed form in this scenario was not elegant and the workload was huge. To solve this problem, we can dynamically display the parameters required by the course classification form when adding courses, obtain the input course parameters, construct data, and perform storage operations.

Display categories through components

<!-- reply.vue -->
<template>
  <div>
    <li>
      <div v-if="data.id != 0" @click="getfid(data.id)" :id="data.id"> {{ data.name }}</div>
      <ul v-if="data.children && data.children.length > 0">
        <Reply v-for="child in data.children" :key="child.id" :data="child"/>
      </ul>
    </li>
  </div>
</template>

<script>

  import bus from './bus.js';

  export default {

    //Declare name name: "Reply",
    props: ['data'],
    //Declare components components: {},
    //Declare variable data() {
      return {
        fid: 0,
      }
    },
    //Custom filters filters: {
      myfilter: function (value) {
        value = value.slice(0, 3);
        return value + "********";
      }
    },
    // Initialization method mounted() {
    },
    //Declare methods methods: {
      //Click on the category id
      getfid: function (fid) {
        this.fid = fid;
        //console.log(this.fid);
        bus.$emit("msg", fid);
        localStorage.setItem("fid", this.fid);

        //Cancel all highlights var divs = document.getElementsByClassName("bg");

        //Traverse the selector for (var i = divs.length - 1; i >= 0; i--) {

          //Cancel highlight divs[i].classList.remove("bg");

        }
        //First, highlight the current element var mydiv = document.getElementById(fid);
        //Dynamically add highlight class selector mydiv.classList.add("bg");
      }
    }
  }
</script>


<style>

  ul {
    padding-left: 10rem;
    list-style: none;
  }

  .bg {
    background: orange;
    color: white;
  }
</style>

Use third-party components to monitor category IDs

<!--bus.js-->
import Vue from 'vue'

export default new Vue();

Add Course Page

<template>
  <div>
    <heads></heads>
    <h1>Course Submission Page</h1>
    <reply :data="mydata"/>
    <van-cell-group>
      <van-field label="Course Title" v-model="title"/>
      <van-field label="Course Description" v-model="desc" rows="5" type="textarea"/>
      <van-field label="Course Price" v-model="price"/>

      <div v-for="(value,key,index) in params">
        <van-field :label="key" v-model="info[key]"/>
      </div>

      <van-button color="gray" @click="addcourse">Save course</van-button>
    </van-cell-group>
  </div>
</template>

<script>

  //Import other componentsimport bus from './bus.js';
  import reply from "./reply";
  import heads from "./heads";


  export default {

    //Declare components: {
      'reply': reply,
      'heads': heads,
    },
    //Constructor created() {
      //Monitor bus.$on('msg', target => {
        console.log(target);
        this.fid = target;
        if (this.cid === 0) {
          this.get_cate(this.fid)
        } else {
          this.$toast.fail("You have already saved the course and cannot select the category again");
          return false;
        }
      });
    },
    //Declare variable data() {
      return {
        //data mydata: {},
        //Course category id
        fid: localStorage.getItem("fid"),
        title: "",
        price: "",
        desc: "",
        cid: 0,
        videos: [],
        videosrc: "",
        params: {},
        info: {}
      }
    },
    // Initialization method mounted() {
      this.get_data();
    },
    //Declare methods methods: {
      get_cate(fid) {
        this.axios.get('http://localhost:5000/getcate/', {params: {'fid': fid}}).then(result => {
          var myparams = result.data.params;
          if (myparams === '') {
            myparams = null
          }
          myparams = JSON.parse(myparams)
          this.params = myparams

          for (var key in this.params) {
            this.$set(this.info, key, '')
          }
          console.log(this.info)
        })
      },
      //Add course addcourse: function () {
        var lists = [];
        for (var key in this.info) {
          lists.push({'key': key, 'value': this.info[key], 'label': this.params[key]})
        }

        var list_str = JSON.stringify(lists)

        var data_post = {
          fid: this.fid,
          title: this.title,
          desc: this.desc,
          price: this.price,
          id: localStorage.getItem("user_id"),
        }
        if (lists.length > 0) {
          data_post = {
            fid: this.fid,
            title: this.title,
            desc: this.desc,
            price: this.price,
            id: localStorage.getItem("user_id"),
            params:list_str
          }
        }

        this.axios.post(
          'http://localhost:5000/addcourse/',
          this.qs.stringify(data_post)).then((result) => {
          if (result.data.code === 200) {
            this.$toast.success('Course added successfully');
            this.cid = result.data.cid;
          } else {
            this.$toast.fail(result.data.msg);
          }
        });
      },
      //Get data get_data: function () {
        //Send request this.axios.get(
          'http://localhost:5000/catelist/').then((result) => {
          console.log(result);
          //Declare the root node var mytree = {'id': 0, name: ""};
          mytree['children'] = result.data;
          this.mydata = mytree;
          console.log(this.mydata);
        });
      }
    }
  }
</script>


<style scoped>

  ul {
    padding-left: 10rem;
    list-style: none;
  }

</style>

summary

To put it simply, when we select a category when adding a course, the parameters that we must pass under that category will be dynamically displayed in the form of a form, allowing users to add courses and improve efficiency.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue dynamic form development method case detailed explanation
  • Generate dynamic forms using Vue
  • Strategy mode to implement Vue dynamic form validation method
  • Detailed explanation of Vue+Element's dynamic form, dynamic table (backend sends configuration, front-end dynamically generates)
  • Implement dynamic form validation function based on Vue+elementUI (dynamically switch validation format according to conditions)
  • Example of how to build dynamic forms in Vue
  • How to implement dynamic form addition, deletion, modification and query examples in vue2
  • Vue+ElementUI realizes the method of dynamic rendering and visual configuration of forms
  • Vue+Element realizes dynamic generation of new forms and adds verification functions
  • Vue+element to dynamically load the form

<<:  Rules for registration form design

>>:  Mysql 5.6 "implicit conversion" causes index failure and inaccurate data

Recommend

Explanation of the usage of replace and replace into in MySQL

MySQL replace and replace into are both frequentl...

How to dynamically add a volume to a running Docker container

Someone asked me before whether it is possible to...

How to install MySQL 8.0.13 in Alibaba Cloud CentOS 7

1. Download the MySQL installation package (there...

How to limit the number of records in a table in MySQL

Table of contents 1. Trigger Solution 2. Partitio...

HTML+CSS project development experience summary (recommended)

I haven’t updated my blog for several days. I jus...

CSS3 realizes text relief effect, engraving effect, flame text

To achieve this effect, you must first know a pro...

Detailed explanation of the this pointing problem in JavaScript

Summarize Global environment ➡️ window Normal fun...

Learn more about MySQL indexes

1. Indexing principle Indexes are used to quickly...

Additional instructions for using getters and actions in Vuex

Preliminary Notes 1.Differences between Vue2.x an...

How to use regular expression query in MySql

Regular expressions are often used to search and ...

An article to understand the usage of typeof in js

Table of contents Base Return Type String and Boo...

Methods and steps for deploying multiple war packages in Tomcat

1 Background JDK1.8-u181 and Tomcat8.5.53 were in...

What we can learn from Google's new UI (pictures and text)

The most significant website change in 2011 was Go...

How to create a web wireframe using Photoshop

This post introduces a set of free Photoshop wire...

Details on how to write react in a vue project

We can create jsx/tsx files directly The project ...