Enhancing late-bound properties in vue.js with custom getters and setters

This particular issue pertains to the following query: map two 1D arrays into a 2D array and then fill with known values. Essentially, I am working with three sets of data: Colours, Sizes, and Products. These datasets are loaded into the Vue main component using axios to fetch information from an API. Each product in the collection references a color and size object. In my previous inquiry mentioned above, I sought guidance on structuring products into a 2-dimensional array based on colors and sizes (even if not all combinations exist). My current dilemma revolves around managing the application state until it's time to save the changes back to the datastore.

The code snippet below illustrates how products are arranged in the grid within a method of the primary Vue component:

buildDimensions(){
/* create a new array where SKU acts as a key to map them into the grid */
    currentSKUs = this.style.skus.reduce((currentSKUs,sku) => currentSKUs.set(sku.sku,sku),new Map);
    result = this.style.colours.map(
        colourRow => this.style.sizes.map(
            sizeColumn => ({
                key: this.style.name.trim() + colourRow.colour_code.trim() + sizeColumn.size_code.trim(),
                value: currentSKUs.get(
                    this.style.name.trim() + colourRow.colour_code.trim() + sizeColumn.size_code.trim()
                    ) || {
                             colour_code: colourRow.colour_code.trim(),
                             size_code: sizeColumn.size_code.trim(),
                             lifecycle: "Not Created",
                             sku:this.style.name.trim() + colourRow.colour_code.trim() + sizeColumn.size_code.trim(),
                             selected:false
                         }
                        })
                    )
                );
    this.matrix = [];
    this.matrix.push(result);
},

My objective is to generate a new object with a 'selected' property set to false for non-existent products. This functionality appears to be functioning correctly. However, I'm encountering issues with updating the UI when modifying the 'selected' property for existing SKUs. It seems that the getters and setters are not being properly created for this property addition.

I've attempted solutions like:

Vue.set(sku,selected,false) 

and

sku = Object.assign({}, sku,{selected:false}) 

while iterating over the API results before saving them to the data object, but these methods didn't yield the desired outcome.

If anyone can offer insights or suggestions on how to implement the properties while ensuring the appropriate getters and setters are in place, I would greatly appreciate it. It's worth noting that the 'selected' property is purely for UI purposes and should not be persisted in the data store.

Answer №1

In my recent troubleshooting, I managed to resolve the issue in a somewhat unconventional way that proved effective for my needs. What I did was intercept the API response and looped through each item in res.data to add a selected:false property to it.

.then((res) => {
         for(sku of res.data){
             sku = Object.assign(sku, {selected:false});
         }
         app.style.skus = res.data;
      }
)

An important thing to note is that although I added the selected property to the data object itself, I only accessed it from a specific child component, as the data collection represented a subset of all possible records. This workaround might be useful for someone encountering a similar situation.

To ensure proper reactivity in Vue, it's crucial to inject any additional properties before adding the records to the data() function. This allows Vue to generate getters and setters for the objects when they are initially included, ensuring that event watchers are triggered properly. Without this step, adding properties after creation may result in lost reactivity due to missing getters and setters.

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

"Setting the minimum length for multiple auto-complete suggestions in

How can I dynamically set the minLength of an input field based on whether a numeric value is coming from the "#lookup" field? Is there a way to achieve this using JavaScript and jQuery? <script type="text/javascript"> $(document).ready(function() ...

Setting the role attribute as "status" dynamically using VueJS

I'm searching for a method to define the role="status" attribute with vue.js. For instance: :role="{'status': isStatus}" <span class="result-total" role="status"> <span class="result-n ...

How to utilize 'this' in a Vue template?

I'm feeling confused: I came across information stating that we can use this in Vue.js templates. But now I'm unsure about which one to use. I decided to experiment with some cases here: new Vue({ el: "#app", data: function() { return { ...

Adjusting the alignment of a facial image on Canvas by selecting specific click-points

I have a unique idea for an app that allows users to correct a tilted face with just 2 clicks The concept is simple - users click on the middle of the nose and the middle of the eyebrows within the image to generate two points: eyebrowMiddle(x1,y1) and no ...

What is preventing me from translating JS Canvas Image?

I've been struggling with using ctx.translate() to translate images on a canvas. No matter what I do, it just won't work. I've spent a good amount of time trying to troubleshoot the issue. Here's the snippet of code I'm working wit ...

Implementing Node.js on several domains with the help of express.vhosts()

I'm facing a challenge with my nodejs setup. I am in the process of developing a node server that will support multiple instances of app.js running simultaneously on the same system using express.vhost(). However, I seem to have hit a roadblock. The ...

Having trouble adding the Vonage Client SDK to my preact (vite) project

I am currently working on a Preact project with Vite, but I encountered an issue when trying to use the nexmo-client SDK from Vonage. Importing it using the ES method caused my project to break. // app.tsx import NexmoClient from 'nexmo-client'; ...

Transfer the sockets.io data from the express server file to the route file

When incorporating sockets into a separate route file, I followed the guidance provided in this answer: Express 4 Routes Using Socket.io The implementation mirrors the logic outlined in the server file: var http = require("http"); var admin = require(&ap ...

Can the performance of a system be impacted by node.js cron?

I am looking to incorporate a cron module (such as later or node-cron) into my node server for job scheduling. The jobs in question involve sending notifications (e.g., email) to remind users to update their profile picture if they haven't done so wit ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

What sets apart using `: Interface` versus `as Interface` in Typescript?

I'm struggling to find the distinction between two similar lines of code due to uncertainty about what they are called. Consider the scenario where the following interface is defined: interface Person { name: string; age: number; } What exactly ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...

Using JavaScript to we can transfer the function result to an HTML input field

Is there a way to display the result of a JavaScript function in an HTML input field? Here is an example form: https://i.sstatic.net/HHHl2.png When I click "Run - Script," the following simple script is executed: <button type="submit" class="btn btn ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

Utilize the #value template in PrimeVue Dropdown to retrieve country code for setting the default selected flag

In the student edit modal, I have a Dropdown where I need to display a flag for the default country. When using PrimeVue, I can access the country code from a template using #option="slotProps", but not with #value="slotProps". This m ...

Using Redis for pub/sub functionality within or outside of the io.connect callback

Is it preferable to move the redis subscription event outside of the io.connect callback if the intention is to broadcast the data to all connected users? Or would it be better to keep it inside the io.connect callback, as shown below: io.on('con ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Display a pre-set placeholder option in a select dropdown using VueJS

I am having trouble setting a pre-selected and disabled placeholder in a select element using VueJS. I want "Choose your saved prescription" to be the default option when the page loads, but currently it shows a blank select with the placeholder as an op ...

Exploring Node.js: Managing Memory Consumption for Efficiency

I'm currently setting up multiple Node applications on one server, and I'm particularly worried about memory usage. Is there a specific amount of physical memory needed for a basic Node.js express service to run? Also, is there a method to limit ...

Messy code appeared when sending an AJAX post to JBoss EAP 7 without using encodeURIComponent

Initially, the project functions smoothly on tomcat using UTF-8 and jboss eap 6 with UTF-8 page encoding as well. Additionally, the jboss configuration includes: <servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="loc ...