Leveraging the power of Nuxt.JS (Vue.JS) and VueX to connect a form to an array of objects within a VueX store

Seeking assistance with binding a form to a list of Defaultsettings obtained from an array of objects in NuxtJs and VueX. The list of Defaultsettings includes:

  • Name defaultsetting (text)
  • Active (a switch button that determines if the defaultsetting will be active or not - boolean)
  • Mandatory (a radio button that determines if the defaultsetting will be required or not - boolean)

A server-side call using Axios retrieves the list of defaultsettings which are then dispatched to the jobs store in the following manner:

asyncData(context) {
    return context.app.$axios
        .$get('jobs/create')
        .then(data => {            
            context.store.dispatch('jobs/getDefaultsettings', data.defaultsettings)
        })
        .catch(e => context.error(e))
},

The 'getDefaultsettings' function in jobs.js handles the incoming data:

getDefaultsettings(context, data) {
    context.commit('setDefaultsettings', data)
},

The 'setDefaultsettings' mutation within getDefaultsettings sets the received data accordingly:

setDefaultsettings(state, data) {

data.forEach(function(d) {
    d.mandatory = false
    d.active = false
})
state.defaultsettings = data
},

To ensure the defaultsettings are available in the data, they are stored in the created function as shown below:

created() {
this.ruleForm.defaultsettings =  this.$store.state.vacatures.defaultsettings

}

However, confusion arises when trying to bind the data. Reference was made to an example found at https://vuex.vuejs.org/guide/forms.html, but encountering an error stating "Cannot read property 'mandatory' of undefined".

<div class="row" v-for="defaultsetting in ruleForm.defaultsettings " :key="defaultsetting.id">
<div class="col-sm-4">
{{defaultsetting.name}}
</div>
<div class="col-sm-4">
<el-checkbox v-model="defaultsetting.mandatory" :value="mandatory" @input="updateMandatory"/>
</div>

Added a computed property for 'mandatory':

computed: {
mandatory () { return this.$store.state.vacatures.defaultsetting.mandatory }
},

Additionally, methods were implemented:

methods: {

updateMandatory (e) {
    this.$store.commit('updateMandatory', e.target.value)
},
},

In jobs.js, a new mutation 'updateMandatory' was introduced:

updateMandatory (state, setting) {
state.defaultsetting.mandatory = setting
},

Any guidance on resolving this issue would be highly appreciated!

Answer №1

Struggling to get vuex-map-fields working smoothly with Nuxt.JS, I decided to directly map the store data in the created() hook.

        created() {
        this.ruleForm.defaultsettings =  this.$store.state.jobs.defaultsettings.map((obj) =>  Object.assign({}, obj))

    }

After this mapping, I am able to easily manipulate the state by using v-model when iterating through ruleForm.defaultsettings.

<div class="row" v-for="(defaultsetting, index) in ruleForm.defaultsettings " v-if="defaultsetting.groupsequence === 1"  >
                        <div class="col-sm-4">
                            {{defaultsetting.label}}
                        </div>
                        <div class="col-sm-4">
                            <el-switch
                            style=""
                            v-model="ruleForm.defaultsettings[index].active"

                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            />
                        </div>
                        <div class="col-sm-4" v-if="ruleForm.defaultsettings[index].active === true">
                             <el-checkbox v-model="ruleForm.defaultsettings[index].mandatory"  />
                        </div>
                    </div>

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

Configuring Webpack for a React application with Express and Babel

I am in the process of developing a React application, utilizing React version ^15.6.1 along with Webpack, Express, Babel, and Yarn as the package manager. After successfully running the application, I am now preparing to transition it to production by co ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

Unlock the capability to automatically swipe on a React Native TextInput Carousel while the user types

My challenge involves setting up a carousel with either Flatlist or ScrollView (I have tested both options). This Carousel consists of multiple TextInputs. The goal is to achieve the following: There are 4 TextInputs. When the user enters 6 digits in the ...

The data in the second run of the jQuery datatable does not refresh successfully

I have encountered an issue while trying to load data from the server. It works perfectly on the initial load, but upon reloading, it fails to function. Please bear with me as this is a legacy project. Even after attempting a normal call and refreshing th ...

After deploying to Firebase, animations suddenly cease to function

After running npm run-script build and deploying my React app to Firebase hosting with firebase deploy, I encountered an issue where my animations stopped working. I'm puzzled as to why this is happening, especially since I've included keyframes ...

The @Prop property decorator in Vue cannot be utilized as it is not compatible

I have a Vue 2 component with TypeScript: import Vue from 'vue'; import Component from 'vue-class-component'; import Prop from 'vue-property-decorator'; @Component({ template: require('./template.html'), }) expo ...

Is there a way to retrieve information from a prior session without relying on cookies?

One of my projects involves entering a name and selecting checkboxes on a page, with the data being saved to a text file on the server using PHP. To retrieve the data for a specific name, I use the following PHP code: <?php $search = $_GET["name"]; $c ...

How to use Yii2 to trigger a controller action from a view and effectively debug the

Within a data grid view, there is a text input field where I intend to trigger a controller function when the field is updated. To achieve this, I have embedded a script in my form and set up a controller function. $this->registerJs( "$('#prod ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

Using Javascript to dynamically flash-highlight text on a webpage when it first loads

I am looking to create a special highlight effect that activates when the page loads on specific text. Let's focus on the element with id="highlight me". The highlight should glow twice around the selected container before fading out. For a clear unde ...

Obtain a Compilation of Video Sources in an HTML5 Format

Hey there, I am using an HTML5 video. This is just an example <video width="320" id="video" height="240" controls> <source src="video.mp4" type="video/mp4"> <source src="video1.mp4" type="video/mp4"> <source src="movie.ogg" typ ...

Is it possible to employ the 'index' parameter within a 'v-for' loop that is nested inside a 'method'?

Is it possible to use the index on a v-for directive at the same level as the directive itself in order to manipulate the state being displayed? <template> <div> <div v-for="share in sharesPurchased()" :key="share"> <div&g ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Using a for loop to cycle through an array and generate sibling div elements

I'm attempting to display the content of the gameTwo array in two child divs under the game2 element. However, the issue I'm facing is that the loop creates a child of a child on the second iteration. Could someone provide guidance on how I can a ...

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

The jQuery DataTable is repeatedly triggering when attempting to conceal columns

Update Here is an additional example, consisting of just a few lines of code... triggering the alert twice! $(document).ready( function () { var x = $('#example').dataTable( { fnRowCallback: function( nRow, aData ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...