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

Detailed explanation of Vue mixin usage and option merging

Table of contents 1. Use in components 2. Option ...

A brief discussion on ifnull() function similar to nvl() function in MySQL

IFNULL(expr1,expr2) If expr1 is not NULL, IFNULL(...

MySQL 8.0.18 adds users to the database and grants permissions

1. It is preferred to use the root user to log in...

Network configuration of Host Only+NAT mode under VirtualBox

The network configuration of Host Only+NAT mode u...

Vue3 slot usage summary

Table of contents 1. Introduction to v-slot 2. An...

HTML implementation of a simple calculator with detailed ideas

Copy code The code is as follows: <!DOCTYPE ht...

Vue Basic Tutorial: Conditional Rendering and List Rendering

Table of contents Preface 1.1 Function 1.2 How to...

MySQL merge and split by specified characters example tutorial

Preface Merging or splitting by specified charact...

Web design reference firefox default style

Although W3C has established some standards for HT...

How to optimize MySQL index function based on Explain keyword

EXPLAIN shows how MySQL uses indexes to process s...

border-radius is a method for adding rounded borders to elements

border-radius:10px; /* All corners are rounded wi...

Do you know what are the ways to jump routes in Vue?

Table of contents The first method: router-link (...

Method for comparing the size of varchar type numbers in MySQL database

Create a test table -- --------------------------...

How to use Linux whatis command

01. Command Overview The whatis command searches ...