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 HTML form elements (Part 1)

HTML forms are used to collect different types of...

Markup Language - Title

Click here to return to the 123WORDPRESS.COM HTML ...

MySQL cursor detailed introduction

Table of contents 1. What is a cursor? 2. How to ...

Answers to several high-frequency MySQL interview questions

Preface: In interviews for various technical posi...

Analyze the working principle of Tomcat

SpringBoot is like a giant python, slowly winding...

Modify the style of HTML body in JS

Table of contents 1. Original Definition 2. JS op...

About the pitfalls of implementing specified encoding in MySQL

Written in front Environment: MySQL 5.7+, MySQL d...

Reasons why MySQL queries are slow

Table of contents 1. Where is the slowness? 2. Ha...

Examples of using MySQL pessimistic locking and optimistic locking

Pessimistic Lock Pessimistic lock, considers the ...

Solution to the img tag problem below IE10

Find the problem I wrote a simple demo before, bu...

vue-amap installation and usage steps

I have previously shared the usage of asynchronou...

Xhtml special characters collection

nbsp &#160; no-break space = non-breaking spa...

How to install phabricator using Docker

I am using the Ubuntu 16.04 system here. Installa...

A brief introduction to MySQL dialect

Putting aside databases, what is dialect in life?...