Generating a dynamic list of reactive checkboxes in vue.js using data from API call

I'm currently working on a vue.js component that utilizes a search field to query the Google Places API (for simplicity, I've removed some details). The response from the API is a list of checkboxes representing different places. My goal is to set a flag checked to true on the selected object when a user checks a place.

However, I've encountered an issue where I want this property to be reactive, but it seems adding reactive properties at runtime does not work as expected (refer to https://vuejs.org/guide/reactivity.html).

<template>
  <form>
    <input type="text" ref="complete" v-bind:placeholder="placeholder">
    <fieldset v-if="places" class="checklist">
      <h4>Select your store locations:</h4>
      <div v-for="place in places">
        <input :id="place.id" type="checkbox" v-model="place.checked">
        <label :for="place.id">
          {{ place.name }}<br>
          <span class="subtext">{{ place.formatted_address }}</span>
        </label>
      </div>
    </fieldset>
  </form>
</template>
<script>
  export default {
    data() {
      return {
        places: [],
        api: {
          domain: 'https://maps.googleapis.com/maps/api/js',
          key: 'API Key',
          libraries: 'places',
        },
      };
    },
    mounted() {
      window.onload = this.loadScript(
        `${this.api.domain}?key=${this.api.key}&libraries=${this.api.libraries}`,
        this.bindAutocomplete
      );
    },
    watch: {
    },
    methods: {
      loadScript(src, callback) {
        const script = document.createElement('script');
        document.body.appendChild(script);
        if (callback) {
          script.onload = callback;
        }
        script.src = src;
      },
      bindAutocomplete() {
        this.autocomplete = new google.maps.places.SearchBox(
          this.$refs.complete
        );
        this.autocomplete.addListener('places_changed', this.pipeAddress);
      },
      pipeAddress() {
        this.places = this.autocomplete.getPlaces();
      },
    },
  };
</script>

The component seems to function properly, however, I'm unable to programmatically set any checkboxes to "checked", for example using

this.places.forEach((place) => { place.checked = true; }
. How can I achieve this in a proper manner?

Thank you,

Henning

Answer №1

Make sure to define the checked property before the data is observed, meaning it should be added to the data object beforehand.

An effective approach is to modify the places object within the array generated by the getPlaces() function to include the checked property prior to assigning it to a key in the data object.

pipeAddress() {
    this.places = this.autocomplete.getPlaces().map(
        place => { place.checked = false; return place }
    );
},

By doing so, the checked property will be available when the data is observed, making it reactive and allowing the DOM to update accordingly.

Check out this fiddle

Further explanation provided on Vue blog:

If you add a new property that wasn't initially present when the data was observed, Vue.js may not detect these property additions or deletions due to ES5 limitations. It's recommended to declare reactive properties upfront. In cases where dynamic addition or deletion of properties is necessary, use Vue's global Vue.set or Vue.delete methods.

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

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

Selection box and interactive buttons similar to those found in Gmail

Looking to achieve these effects for <option> and <button> using CSS and JavaScript. Any suggestions on how to do this? ...

What could be causing my Vuex store state to consistently come up empty in middleware when accessing it through SSR (Server-Side Rendering) with NuxtJS?

Question: I am facing an issue with my middleware files. More specifically, I have a file named authenticated.js. In this file, I have a function that checks for authentication. Here is the code snippet: export default function (context) { //console.l ...

Looking to scan through a directory of .html files in Node.js to find specific element attributes?

Imagine trying to tackle this task - it's like reaching for a needle in a haystack. Picture a folder containing a static website, complete with images, stylesheets, and HTML files. My Node application needs to dive into this folder and extract only th ...

Learn the process of adding a key and value into an array using Angular

I need to filter data based on the number of rows and columns provided by the user. After reading an excel file, I extract the data in the controller: https://i.sstatic.net/vPpxL.png These are the column headers retrieved after the user entered 5 as the ...

Guide to Retrieving 'req' in JavaScript within Node.js / Express Framework

I have a loaded page named tournament/:key, where a Tournament object is passed. The Jade template accesses variables from the Tournament using syntax like #{tournamentData.name} to display the data on the page. The list of matches is stored as an array wi ...

Having trouble with jQuery focus not functioning properly?

I've been attempting to implement a focus function on a specific input in order to display a div with the class name .search_by_name when focused. However, I'm encountering issues and would appreciate it if someone could review my code to identif ...

Issue with Webpack dev middleware failing to serve bundle.js appropriately

Currently, I am in the process of developing my very own redux starter kit and have been making some updates to it. However, I have encountered an issue where my bundle.js (and style.css) are not being properly served on the page by webpack-dev-middleware. ...

Using Regular Expressions in JavaScript to verify if an element from an array is contained within a string

Looking for a simple JavaScript code for a Vue application that will split the string into an array and check if any value is present in a different string. Here's what I have: let AffiliationString = " This person goes to Stony Brook" ...

Objects cannot be rendered inside JSX. An error is thrown stating that Objects are not allowed as a React child, with the specific object being [object Promise]

Within my React project, I have a Class-based component that serves as a child component. The state it relies on is passed down from a parent component. Within the JSX of this component, there is a map function that iterates over a platformsList array. Whi ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

Changing model to array in mvc 3

I have a model that I would like to convert into an array by clicking on a button to execute a JavaScript function. The function will then send the array to a controller that will either read and parse the data as JSON or simply as a Model. For example: ...

Utilizing jQuery to place an element beside another and maintain its position

I need ElementA to be positioned next to ElementB as shown in this example. The key difference is that I want ElementA to move along with ElementB if the latter is relocated. Is there a way to keep a specific element fixed to another one? Re-calculating ...

Tips for creating a well-written piece of writing

sendoptions ={method : "PUT", credentials: 'same-origin', header :{"Content-Type":"application/json"}, body: JSON.stringify(Cookies.get("accessToken")} } body: JSON.stringify(Cookies.get("accessToken ...

Vue Component fails to update object changes even after using $set

I am working on creating a customized Vue component that showcases the hour and minute of a specific Date object. The goal is to generate a modified version when either the plus (+) or minus (-) button is clicked. Screenshot reference: https://i.sstatic.n ...

Creating a condensed version of the process: Utilizing jQuery for thumbnail preview on hover to create an image slideshow

I've created a video preview slideshow function using jQuery. As a newcomer to jQuery, I'm questioning if there's a more efficient way to achieve this. Having separate timers for each frame feels cumbersome and limits the flexibility in chan ...

Implementing Ajax to insert information, however, the process is prolonged for data insertion

When I use AJAX to insert data into MySQL, pressing the submit button is causing delays in data insertion. I'm hoping someone here can provide better suggestions or feedback. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

When using the `survey-react` package, there seems to be an issue with the `this.addEvent

Upon inheriting a React project, I am facing difficulty in utilizing the survey-react module. Every time I access http://localhost:3000/, I encounter this error: Uncaught TypeError: this.addEvent is not a function node_modules/survey-react/survey.react.js: ...