Is there a way to fill in automatically generated input fields with Vue.js and Laravel?

It's been only 2 weeks since I started working with Vue, and so far, everything is going smoothly. However, I'm facing a challenge that I could use some help with.

I need to create a series of select inputs based on options retrieved from the database for user preferences. Sometimes, the user may have already made selections for some or all of these options.

The issue I'm encountering is that I can't figure out how to populate the generated select inputs with the user's current choices.

I had it working perfectly until I introduced auto-generation of the inputs. Below is my code snippet - any assistance provided would be greatly appreciated. If you require more information, please feel free to ask. I believe my objective is quite clear, but it appears that the Vue code is overwriting the values and rendering them blank during generation.

Code in the blade.php

<div class="form-group row" v-for="preference in preferences">
   <label class="col-md-4 col-form-label text-md-right">
       @{{ preference.name }}
       <span v-if="currentPreferences[preference.id] && currentPreferences[preference.id].value">
            <br /> (current: @{{ currentPreferences[preference.id].value }})
       </span>
   </label>
   <div class="col-md-6">
      <select class="form-control" @change="updatePreferences(preference)" v-model="selected[preference.id]">
         <template v-if="currentPreferences[preference.id] && currentPreferences[preference.id].value">
            <option disabled value="">Please select one</option>
            <option v-for="item in preference.options" :value="item" :selected="item == currentPreferences[preference.id].value">@{{ item }}</option>
         </template>
         <template v-else>
            <option disabled value="">Please select one</option>
            <option v-for="item in preference.options" :value="item">@{{ item }}</option>
         </template>
      </select>
   </div>
</div>

Code in hero-preferences.js

Vue.component('dashboard-preferences', {
    props: ['user'],

    data() {
        return {
            preferences: [],
            currentPreferences: []
        };
    },

    mounted() {
        this.getPreferencesData();
    },

    methods: {
        getPreferences() {
            axios.get('/dashboard/preferences')
                .then(response => {
                    this.preferences = JSON.parse(response.data);
                })
                .catch(response => {
                    this.preferences = [];
                });
        },
        getCurrentPreferences() {
            axios.get('/dashboard/preferences/current')
                .then(response => {
                    this.currentPreferences = JSON.parse(response.data);
                })
                .catch(response => {
                    this.currentPreferences = [];
                });
        },
        getPreferencesData() {
            this.getPreferences();
            this.getCurrentPreferences();
        }
    }
});

Code in email-preferences.js (sub-component)

Vue.component('dashboard-hero-preferences-email-preferences', {
    props: ['user','preferences','currentPreferences'],

    data() {
        return {
            updated: null,
            selected: [],
            updatePreference: null
        };
    },

    methods: {
        updatePreferences(preference) {
            this.updatePreference = preference;

            axios.post('/dashboard/preferences/update', {
                preference: preference.id,
                value: this.selected[preference.id]
            })
            .then(() => {
                this.$emit('update');
                this.updated = 'yes';
            });
        }
    }
});

Thank you, David

Answer №1

After receiving some guidance from @luceos, I was able to resolve the issue in email-preferences.js by implementing the mounted method as shown below.

mounted() {
        let info = null;
        axios.get('/dashboard/preferences/current').then((response) => {
            info = JSON.parse(response.data);

            Object.keys(info).forEach(item => {
                this.selected[item] = info[item].value;
            })
        })
    },

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

What is the best way to sort search results using various criteria?

Currently, my search filter is only able to filter results based on the 'packageName' field. I now have a requirement to expand this filter to also include the 'dateStart' and 'dateFinish' fields. getters: { filteredPacks: ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

Discover and eliminate nested levels

How can I locate and delete a specific value with the ID "5cc6d9737760963ea07de411"? Data: [ { "products" : [ { "id" : "5cc6d9737760963ea07de411", "quantity" : 1, "totalPrice" : 100, ...

Assigning identical values to all properties of an object

Let's consider an object structured like this: myObject = { "a_0" : [{"isGood": true, "parameters": [{...}]}], "a_1" : [{"isGood": false, "parameters": [{...}]}], "a_2" : [{"isGood": false, "parameters": [{...}]}], ... }; The goal is ...

Loading tab content on click using jQuery

These tabs have a chrome-like appearance. When the first tab (Facebook) is clicked, it shows Facebook content. Clicking on the second tab (Twitter) displays the content of the first tab. Tabs three, four, and five show their respective contents without any ...

Implement a unique navigation bar for each page using layout.js in Next.js

https://i.stack.imgur.com/Ha3yC.pngI have a unique setup in my next js project with two different navbar layouts and ten pages. I'm looking to assign navbar one to five pages and navbar two to the remaining pages using layout.js. Can anyone provide gu ...

I am seeking guidance on creating a dynamic search feature using node.js and mongoDb. Any input regarding

I am currently working on implementing a unique feature that involves having an input field on this specific page. This input allows users to perform a live search of employees stored in the database. app.get('/delete' , isLoggedIn , (req , res) ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Encountered an error saying 'TextEncoder is not defined' when running Jest in Next.js version 14

I am currently working on testing some API call methods using Jest in a Next.js 14 environment. Below is my jest.config.js file: const nextJest = require("next/jest"); /** @type {import('jest').Config} */ const createJestConfig = next ...

Adjust the form action and text input name according to the selected radio input

Seeking assistance with the following code, can someone help? $(document).ready(function() { $('#searchform').submit(function() { var action = ''; if($('.action_url').val() == 'l_catalog') { ...

Numerous documents within a JavaScript application

As a newcomer to JavaScript, I've been experimenting with the language to enhance my understanding. One aspect that puzzles me is how developers organize large JavaScript programs. In languages like Java, breaking down code into smaller files is commo ...

Observing attribute changes in AngularJS directives

How can AngularJS observe attributes on a custom directive to bind Angular values? Here is my current progress: <tile title="Sleep Duration" data-value="{{sleepHistory.averageSleepTime}}"/> app.directive('tile', [function() { return ...

How can I clear a text box in Angular.js when the Google Autocomplete event is triggered?

Seeking assistance in AngularJS to clear the textbox value upon triggering the google map autocomplete event. Can anyone provide guidance? Here is the HTML code - <input ng-model="deployText" id="search_execute" class="form-control" type="text" place ...

How to insert a JSON object into a nested array using JavaScript

I am currently facing an issue with adding a JSON object based on specific conditions to an array, which is then used to create a WINJSList. The problem arises when I try to access the elements of the list or array after using the array.push method. My goa ...

Jest snapshot tests using react-test-renderer encounter null references in refs

Having an issue with manually initializing the Quill editor in componentDidMount and encountering Jest test failures. It seems that the ref value I am receiving is null in jsdom. There is a related issue here: https://github.com/facebook/react/issues/7371, ...

preventing users from selecting past dates on Full Calendar Plugin

Is there a way to disable the previous month button on the full calendar? Currently it is April. When I click on the previous button, the calendar shows March instead of disabling. How can this be prevented? http://jsfiddle.net/6enYL/ $(document).ready( ...

Navigating through child components in React

As a newcomer to react application development, I recently embarked on my first project. My goal was to showcase 5 buttons within a table. Initially, I took the straightforward approach of hardcoding them in Table.js Table.js <Button hidden={ ...

Error message displayed: "An error occurred while processing the VueJS InertiaJS Uncaught (in promise) TypeError. It seems that the property 'search'

Currently, I am working on a Vue JS project with Inertia. One of the features I am implementing is a list that allows users to filter by name. data() { return { selectedUser: this.value, selected: null, search: & ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...