Creating conditional v-models for checkboxes in Nuxt using API responses

In my Nuxt 2 project with Nuxt 2 Composition API, I am facing an issue related to displaying items that a user can purchase. Specifically, when a user has previously purchased an item, that item should appear disabled and the checkbox should be checked by default. The API response contains a property called 'has_purchased' which indicates whether the user has bought the item before.

I am struggling to dynamically check the checkboxes based on whether the item has been purchased or not. I have tried various approaches but haven't been successful. Is there a way to make the v-model dynamic so that if 'has_purchased' is true, the checkbox is checked?

Here is a snippet of my single file component:

<template>
    <div class="boost">
        ...
    </div>
</template>
<script lang="ts">
    import { computed, defineComponent, onMounted, ref, watch } from '@nuxtjs/composition-api'
    ...
</script>

One important part is in this section where the checkboxes are disabled if 'booster['has_purchased']', and the issue lies with the v-model for the checkboxes:

<input type="checkbox" v-model="isChecked[index]" :disabled="booster['has_purchased']" />

The original binding for isChecked isn't handling 'booster['has_purchased']', and I've tried different methods without success:

const isChecked = ref<boolean[]>(boostersState.boostersIcons.map(() => false))

The 'boostersIcons' array comes from a store and has this structure:

boostersIcons: [
    {
        id: 'boost-launcher',
        icon: require('~/assets/images/upsell/boost/icons/launcher-icon.svg'),
        has_purchased: true,
    },
    ...
]

And here is how the API response data looks like after being transformed into a computed property within the component:

[
    {
        "code": "boost-launcher",
        "name": "Launcher",
        "price": "12",
        "formatted_price": "£12",
        "currency_symbol": "£",
        "has_purchased": false,
        ...
    },
    ...
]

If anyone can provide guidance or assistance with resolving this issue, it would be greatly appreciated.

Answer №1

To successfully update the checkboxes based on a certain property in the state, it was essential to monitor any changes in the store first. By checking the type of data and ensuring the state exists before assigning a new array of elements, the "checked" state of the checkboxes can be adjusted accordingly using the "on_purchased" property.

    watch(
        () => boostersState.boostersData,
        (newBoostersData) => {
            boostersData.value = newBoostersData
            if (newBoostersData && typeof newBoostersData === 'object') {
                isChecked.value = Object.values(newBoostersData).map((booster: any) => booster['has_purchased'])
            }
        },
        { deep: true }
    )

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

Displaying Elements of a JSON Array using v-for

I am currently working with an API that stores my Data in JSON format. While I am able to successfully load and display the entire array, I am facing challenges in displaying specific fields. The array is located in a field: peoples: '&ap ...

I am having trouble programmatically setting the 'checked' attribute for a newly added checkbox on an asp.net page

I dynamically added checkboxes using jQuery on my ASPX page and attempted to check some checkboxes by default based on conditions. However, I encountered the following error: Uncaught TypeError: undefined is not a function I tried the following methods ...

Header-driven redirection

I am using node js and express js. My goal is to ensure that if app.get does not have a token parameter, then an html file with js will be uploaded to pass the token. If the token is passed, then another html file should be displayed. However, I am unsure ...

Issue with jQuery DataTable: Unable to use column-level filters at the top and maintain a fixed height simultaneously

I am having an issue displaying data in a jQuery DataTable with a column level filter at the top, fixed height, and scroller enabled. Initially, I was able to display the column level filter at the top and it was functioning properly. However, when I set t ...

Is it necessary to distinguish between JS and PHP objects in an interaction diagram?

Currently, I am working on developing a communication diagram for an application that facilitates the purchase of books. Employing domain-driven design principles, my project involves three main objects: 'shop,' 'cart,' and 'book.& ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

Using JavaScript, learn how to dynamically add a `<select class="form-control">` in Bootstrap

Currently delving into the realms of Bootstrap and jQuery, these are both new territories for me. I am looking to use JavaScript to dynamically create the <select class="form-control"> tag. In my JavaScript code snippet, I have this: var response ...

Encountering various issues while running vue create and npm run serve commands

Recently, I started working with Vue and encountered several errors while trying to create new projects using vue create and running npm run serve. I attempted to resolve the issues by reinstalling node and vue, as well as adjusting some PATH configuratio ...

String array in JavaScript

I'm puzzled by a strange issue I've come across. Here's what's happening: I declare an array called status=new Array(). Then, I loop through from 0 to N-1, and assign status[i]="idle";. When I try to check the values using alert, they a ...

How to showcase the date in a unique format using Angular

Does anyone know of a JavaScript ES7 method that can convert the output of new Date() into the format shown below? If there isn't a built-in method, I am willing to manually parse or find/replace it myself. 2020-06-30 07.49.28 I would like the da ...

Tips for activating a text box by pressing a key without actually typing the key into the box

Is there a way to focus on a text box whenever the user presses the 'S' key on the keyboard, without actually typing the 'S' character in the text box itself (this issue only occurs in Chrome)? Here is the code I have so far: $(documen ...

Django's "Like" feature with AJAX interaction (duplicate)

Trying to add a like button to my project without reloading the page has been a challenge. I turned to AJAX in JS based on my research, but I'm clueless when it comes to Javascript. Can someone take a look at my code and help me out? Or maybe t ...

Tips for presenting JSON data retrieved using jQueryWould you like to know how

Is there a way to extract and display the user id from JSON values? I'm trying to access the user id value. $('User_id').observe('blur', function(e) { var txt = $('User_id').value; jQuery.ajax({ type: 'g ...

Switching Databases in MongoDB after establishing a connection using Express - A guide

I am currently using Express to establish a connection with my MongoDB database: mongodb.MongoClient.connect(mongourl, function(err, database) { // Is there a way to switch to another database at this point? }); In the initial setup, I have to co ...

Utilizing the random function in a loop can result in unpredictable and unexpected values

Why is it that I get numbers ranging from 17 to 70,000 in the three console.log statements? However, in the loop, y always seems to fall between 200 and 800. Why is that? console.log("RND " + Math.floor(Math.random()*5000)*17) console.log("RND " + Math ...

`What is the best method for transferring values from JavaScript to C# during page load?`

My approach to solving this issue has been as follows: I added a hidden field on the aspx page named hdnTime. Next, I wrote a JavaScript function to assign a value to the hidden field. <script type='text/javascript'> function getL ...

What method is most efficient for executing a simple CRUD operation with AJAX?

I'm struggling with implementing a basic CRUD on my website. There is a table of records <table> <tbody> <?php foreach ($row as $reg) { ?> <tr <?php if ($reg['value'] < 0) { echo "c ...

Having trouble with Vue 3 Router: outlet not found and content not displaying

In my vue3 application, everything runs smoothly when I include all packages directly in the output bundle locally. package.json "vue": "^3.4.29", "vue-router": "^4.3.3" .... To optimize my bundle size and load t ...

Error: controller undefined

As I delve into a Coursera course on AngularJS, I've encountered a perplexing issue with a controller. The console is indicating that it is not defined. Upon running it through the https://validator.w3.org/, a recurring error message mentioning that ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...