Create a correct v-model value by utilizing a dot notation string as a reference to the data object

Recently, I created a proxy-component that dynamically renders different components based on the specified :type. Everything was functioning smoothly until I encountered an issue with nested objects within the formData object.

An example of this problem is when dealing with test.test1.

I am looking for a way to make the value of v-model dynamic, depending on the provided string.

Here is a snippet of my Component:

<proxy-component
                v-for="(scheme, index) in personSchema.list"
                :key="index"
                :type="scheme.type"
                :props="scheme.props"
                v-model="formData[personSchema.prefix][scheme.model]"
                v-validate="'required'"
                data-vv-value-path="innerValue"
                :data-vv-name="scheme.model"
                :error-txt="errors.first(scheme.model)"
></proxy-component>

And here is the Data section:

data() {
            return {
                selectOptions,
                formData: {
                    person: {
                        given_names: '',
                        surname: '',
                        sex: '',
                        title: '',
                        date_of_birth: '',
                        place_of_birth: '',
                        nationality: '',
                        country_of_residence: '',
                        acting_as: '',
                        test: {
                            test1: 'test',
                        },
                    },
                },
                personSchema: {
                    prefix: 'person',
                    list: [
                        {
                            model: 'given_names',
                            type: 'custom-input-component',
                            props: {
                                title: 'Name',
                            },
                        },
                        {
                            model: 'surname',
                            type: 'custom-input-componentt',
                            props: {
                                title: 'Surname',
                            },
                        },
                        {
                            model: 'test.test1',
                            type: 'custom-input-component',
                            props: {
                                title: 'test 1',
                            },
                        },
                        {
                            model: 'sex',
                            type: 'custom-select-component',
                            props: {
                                title: 'Sex',
                                options: selectOptions.SEX_TYPES,
                                trackBy: 'value',
                                label: 'name',
                            },
                        },
                    ],
                },

            };
        },

Answer №1

I suggest creating a custom method in Vue, specifically under the data section, that generates the object needed for the v-model attribute.

For example:

v-model="generateObject(formData[personSchema.prefix][scheme.model])"
or
v-model="generateObject([personSchema.prefix], [scheme.model])"

This method can help manage dot notation and retrieve the correct nested property when needed.

Answer №2

It doesn't seem to be achievable directly using v-model, but you might find solutions by referring to:

https://v2.vuejs.org/v2/guide/reactivity.html

You could also try implementing a watch function (deep: true) as a workaround. (Consider exploring the usage of watch properties within

formData[personSchema.prefix][scheme.model]
first.)

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

The sum is being treated as a concatenation instead of an addition in this case

Why is the somma value showing the concatenation of totaleEnergetico and totaleStrutturale instead of a sum? RiepilogoCombinatoStComponent.ts export class RiepilogoCombinatoStComponent implements OnInit { constructor() { } interventi: AssociazioneI ...

The jQuery function for AJAX does not properly validate the boolean value provided by the controller

I have a controller action that returns a boolean result to jQuery. [HttpGet] public ActionResult IsVoucherValid(string voucherCode) { bool result = false; var voucher = new VoucherCode(voucherCode); if(voucher.Status==0) ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

Guide on generating a JSON dataset by combining two arrays and sending it back to an AJAX request

key:[id,name,address] value:[7,John,NewYork] I would like to generate a JSON object similar to {"id": 7, "name": "John", "address": "NewYork"} using a for loop, and then send it back to ajax $.ajax({ //what should be ...

Using jQuery to retrieve the nth child from a table after dynamically creating it with AJAX

When using AJAX in the code below, I fill and create simple data after retrieving it. $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: false, success: function (data ...

Tips for managing lag caused by large raw image re-renders in a React application

When trying to change the background position of a user-uploaded background image that is in raw Data URI format using CSS, I noticed that re-rendering becomes slow if the image size exceeds 1mb. This issue does not occur with smaller images. Is there a ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...

How about this: "Can you turn a picture into text with just one click?"

Seeking assistance to enhance the 'About Us' page on our website. Each team member has a profile with their email address listed below, but we want to add a picture that disappears when clicked, revealing the email address in its place. You can ...

Creating a JavaScript interface for an XML API generated by Rails?

Working with a large Ruby on Rails website has been made easier thanks to the REST support in Rails 2. The site's business logic can now be accessed through a consistent XML API. My goal now is to create one or more JavaScript frontends that can inter ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

Newbie in PHP: Techniques for transferring PHP variables between different sections of PHP code

In my project, I have a file named index.php which is responsible for uploading files to the server and setting PHP variables such as $target_folder_and_file_name. This index.php file also includes the following line (originally it was in an index.html fi ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Nuxt.js Button Dropdown Widget

Currently, I am in the process of creating a button similar to a dropdown. This particular button is meant for printing and downloading documents. Here is the code I have implemented: <template> <v-menu transition="s ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

Node.js and react-create-app are not compatible with each other

I am currently using node.js version 14.6.0 and node-v version 7.20.0 To replicate the issue, follow these steps: npx create-react-app my-app2 Once everything is installed, run npm i After completing the above steps, you may encounter the following warn ...

When making xmlhttp requests, IE9 will prioritize loading from the cache rather than from the server when the data is available

During my local development process, I've been utilizing this AJAX code: function getChart(num,ld,margin,idr) { idr = typeof(idr) != 'undefined' ? idr : 0; $(ld).style.display="inline-block"; if (window.XMLHttpRequest) { ...

Disappearing markers issue in Openlayers when zooming

I am trying to ensure that markers on the map do not get erased when zooming in or out. Here is my script: JS $(document).ready(function() { //initialization var map; var markerPosition; // Marker position var options = { restrictedE ...

having trouble compiling a react js file with webpack

One of my files, app.js, contains the following code snippet: handlePageClick = (data) => { let selected = data.selected; let offset = Math.ceil(selected * this.props.perPage); this.setState({offset: offset}, () => { this.setStat ...