Binding Models Dynamically with VueJS

We are currently exploring the use of VueJs 2.0 for our newest project, but we have encountered an early obstacle that we hope to resolve quickly!

Our project involves creating over 150 form fields using Laravel, and we want to bind these parameters to Vue. In our previous experience with Angular 1.4, we used ng-model="form.data.field" to create a comprehensive object to be sent to the backend for processing...

With Vue, it seems like you need to define each field explicitly within the data parameter. We attempted to define an object like this:

data:{
  form: {}
}

This setup works for v-model="form.item", but errors occur when trying to use v-model="form.item.item2".

Is there a way to achieve the same functionality in VueJS?

http://jsbin.com/jafetucuna/edit?html,js,console,output

Answer №1

In a project I'm working on, we have implemented a similar approach. The core fields are predefined, but users can also add their own custom fields which are dynamically rendered. These fields are stored in JSON format within a table called section_schema, consisting of 4 columns: |id | section_name | schema | disable

The schema in the table contains all the necessary information to render the dynamic form effectively. While there might be some complex formatting required for our core data, overall it functions quite smoothly. For brevity, I've omitted the backend preparations involved. Here is an overview:

Sample JSON data in section_schema:

{
   "Company Name":{
      "cols":"8",
      "field_name": "company_name",
      "type":"string",
      "order":"0",
      "required":"1"
   },
   "Member Type":{
      "cols":"4",
      "field_name": "member_type",
      "type":"dropdown_fromdata",
      "order":"1",
      "required":"1",
      "dropdown":{"table" : "membershipType", "field": "name"}
   },
   "Website":{
      "cols":"4",
      "field_name": "company_website",
      "type":"string",
      "order":"2",
      "required":"0"
   },
   ... and more

Within the Vue component:

<div class="col-sm-6" v-for="v in dataType">
   <div class="white-box">
     <h3 class="box-title">{{v.section_name}}</h3>
        <form class="form-material form-horizontal m-t-30" :id="v.section_id">
            <input type="hidden" :value="v.section_id" id="type" name="type">
                 <div class="form-group" v-for="i in v.field_data">
                     <label class="col-md-12" :for="i.id">{{i.name}}</span></label>
                      <div class="col-md-12">
                        <select v-if="i.id === 'company_info-member_type'" class="form-control" style="width: 100%;" size="1" :value="i.value" :id="i.id" :name="i.id">
                          <option value="" selected disabled>Please select</option>
                          <option v-for="mt in membershipTypes" :value="mt.name">{{mt.name}}</option>
                        </select>
                        <select v-else-if="i.id === 'company_info_status'" class="form-control" style="width: 100%;" size="1" :value="i.value" :id="i.id" :name="i.id">
                            <option value="" selected disabled>Please select</option>
                            <option v-for="status in statuses" :value="status.name">{{status.name}}</option>
                        </select>
                       <datepicker v-else-if="i.id === 'company_info-anniversary'" :format="format" :value="setDate(i.value)" :id="i.id" :name="i.id"></datepicker>
                       <input v-else-if="i.type == 'phone'" :type="i.type" :id="i.id" :name="i.id" class="form-control" :placeholder="i.name" :value="i.value" data-mask="(999) 999-9999">
                       <input v-else :type="i.type" :id="i.id" :name="i.id" class="form-control" :placeholder="i.name" :value="i.value">
                      </div>
                 </div>

         <button  @click.prevent="saveMemberChanges(v.section_id)" class="btn btn-info waves-effect waves-light m-r-10">Submit</button>  
     </form>
   </div>
 </div> 

Edit: additional information

Our data:

data () {
        return {
            dataType: [],
        }
},
methods: {
        getDataTypes: function(){
            var id = this.member.id

            this.$http.get('/member/details/json/'+id).then((response) => {
                var data = response.data
                this.dataType = data
            }, (response) => {
               ...
            });
        },
}

Answer №2

A great way to achieve dynamic model binding is by using an array in Vue like this:

<input v-model="formFields[index]" />

You can then create a computed property to map every form input:

  computed: {
    aFormInputName: function() {
      return this.formFields[0].value
    },

This will result in the evaluation of true:

formFields[0] === aFormInputName

For more information on how to implement dynamic v-model, you can refer to this link: https://forum.vuejs.org/t/how-do-i-have-dynamic-v-model/18833

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

What are some strategies for handling analytics tracking in Flux architecture?

Imagine I'm working on a cutting-edge single page application similar to Airbnb. One essential aspect of such an application is keeping track of when someone signs up for an account. There are numerous services available to assist with tracking, incl ...

Ways to showcase Form utilizing function

I've just started learning React JS and bootstrap. I'm attempting to load a login form using a React JS class with an embedded function, but when the function is triggered on click event, it's not rendering the Form and instead displaying co ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

What is the correct way to send a file path with '/' to a Laravel route?

Is there a way to pass a file path to a route like this? <a href={{route('route.name',['path'=>'uploads/xyx/'.$id.'/'.$attachment_name])}}>download</a> My goal is for it to hit Route::get('downlo ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...

The TypeError encountered is with the init function, as it is unable to access the property 'style' of a null

Regardless of how I attempt to write the code, I keep getting the same error message, and I've been working to resolve this issue since last night. However, I can't seem to understand why it's bothering me so much. The error message insists ...

In anticipation of a forthcoming .then() statement

Here is a return statement I have: return await foo1().then(() => foo2()); I am wondering, given that both foo1 and foo2 are asynchronous functions, if the code would wait for the resolution of foo2 or just foo1? Thank you. ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

What exactly is the purpose of calling upon 'express' - a reference to a function or an object?

It is my belief that by utilizing var express = require('express');, the variable express receives a function reference of createApplication(). So, when we invoke express(), it will yield an app object. However, my question is, if var express is ...

How does axios .catch() handle JavaScript errors within Redux middleware?

In my React Redux application, I utilize axios as the client for handling AJAX requests. To manage asynchronous actions, I have implemented middleware that performs the following tasks: Detect promise objects Handle resolving the promise with then() in ...

Changes in the external JavaScript file are not being displayed when the event is triggered

I have included an external JavaScript file in my Master .aspx file like this: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <asp:ContentPlaceHolder ID="head" runat="server"> &l ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

What is the best way to find the index of the smallest value in an array using JavaScript?

I recently created this function that currently outputs -1. function sayHello() { let buildingLevelsArray = [11,10,10]; var smallestIndex = buildingLevelsArray.indexOf(Math.max(buildingLevelsArray)); console.log(smallestIndex); } sayHello() ...

Accessing the parent index in a nested Vue v-for loop

I am facing an issue with a nested v-for. Essentially, I am trying to access the index of the parent v-for and utilize it within the child v-for. <template v-for="(branch, index) in $store.state.agency.branch_users.users"> <table class="tabl ...

Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code: router.get('/', (ctx, next) => { MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) { if (err) th ...

Discover the best way to retrieve attribute values using jQuery

I'm struggling to retrieve the value of the attribute "_last_val" from my input, but I'm having trouble getting it. Here is what I have attempted: demo // Here is the HTML code <form method="post" action="" id="feedback_form"> <inpu ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Tips for setting a data-attribute on the body tag using the current route name in Vue

I have been considering adding a data-attribute to the body of my vue-app that would display the current route's name. I prefer not to utilize the vue-body-class package and want to keep it simple. Currently, I am implementing this in each of my main ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...