How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a time. To achieve this, I created a method named setStarred. Within this method, I use map to set all other cars' starred properties to false before setting the selected car's property to true. However, I am facing an issue where I can successfully set the selected car's property to true, but I struggle to set it back to false.

If you would like to review the code, please visit this Codepen link

This code presents a functioning example:

new Vue({
  el: "#app",
  data() {
    return {
      cars: [{
          name: "Toyota",
          starred: false
        },
        {
          name: "BMW",
          starred: false
        },
        {
          name: "Ford",
          starred: false
        }
      ]
    };
  },
  methods: {
    setStarred(index) {
      this.cars.map((i) => {
        i.starred = false;
      });
      this.cars[index].starred = !this.cars[index].starred;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="304645554459564970011e051e0104">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9dfdcccddc0cfd0e998879c87989d">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout justify-center column>
        <v-flex xs6 v-for="(car,index) in cars" :key="index">
          <h2>{{car.name}}
            <v-icon :color="car.starred ? 'primary': '' " @click="setStarred(index)">star_border
            </v-icon>
          </h2>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</div>

In essence, my aim is to reset the selected car's starred property back to false. Any assistance on this matter would be greatly appreciated. Thank you

Answer №1

Here's a suggestion for your code:

Toggle the starred status of this.cars[index] and update other cars accordingly:
this.cars[index].starred = !this.cars[index].starred;
this.cars.map((car) => {
     if(car.name != this.cars[index].name)
          car.starred = false;
});

Answer №2

I find it more efficient to save the 'starred' status of the target beforehand and then toggle it later.

By doing this, you can eliminate the need for an if statement within the for-loop. While it may not significantly impact performance in this scenario, I believe reducing the number of if statements within a for-loop is a good practice.

Here is an example:

new Vue({
  el: "#app",
  data() {
    return {
      cars: [{
          name: "Toyota",
          starred: false
        },
        {
          name: "BMW",
          starred: false
        },
        {
          name: "Ford",
          starred: false
        }
      ]
    };
  },
  methods: {
    setStarred(index) {
      let cur = this.cars[index].starred
      this.cars.forEach((i) => {
        i.starred = false;
      });
      this.cars[index].starred = !cur;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfb9baaabba6a9b68ffee1fae1fefb">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99f9c8c9d808f90a9d8c7dcc7d8dd">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout justify-center column>
        <v-flex xs6 v-for="(car,index) in cars" :key="index">
          <h2>{{car.name}}
            <v-icon :color="car.starred ? 'primary': '' " @click="setStarred(index)">star_border
            </v-icon>
          </h2>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</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

Updating React component when a property in an array of objects changes by utilizing the useEffect() hook

In my current project, I am creating a React application that resembles Craigslist. In this app, logged-in users can browse through items for sale or services offered. When a user clicks on an item, they are able to view more details and even leave a comm ...

I can't figure out Laravel Passport

Despite reading numerous articles and watching videos on Laravel Passport, I am still struggling to grasp certain concepts. My application works with Laravel 5.5 + vueJs, where all backend requests are made via axios and the routes are located in api.php ...

Retrieve information according to the currency specified

In my database, I have a table of tickets with prices listed in USD. If someone from a country outside the US wants to purchase a ticket, I'd like to display the prices in their local currency for better user experience. However, converting these pric ...

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

Storing the information received from an API as an HTML element

My HTML file contains JavaScript, along with a URL that displays data retrieved from an AWS lambda API call via AWS API Gateway. The page initially appears blank and the data is structured like this: [ {"user": "bob", "groups": ["bobsGroup"], "policies": ...

Ways to incorporate debounce time into an input search field in typescript

Is there a way to incorporate debounce time into a dynamic search box that filters data in a table? I have explored some solutions online, but my code varies slightly as I do not use throttle or similar functions. This is my template code: <input matI ...

What is the best way to animate my logo using JavaScript so that it scales smoothly just like an image logo

I dedicated a significant amount of time to create a unique and eye-catching logo animation for my website! The logo animation I designed perfectly matches the size of the logo image and can be seamlessly integrated into the site. The issue arises when th ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

Sliding out the sidebar menu with Jquery

Hey there! I'm currently working on implementing a swipe feature for the side menu bar. I have already added a click method in my code, but now I also need to incorporate a swipe technique. When the side bar is opened, I want to remove the inside im ...

Implement Acrobat JavaScript to enforce a mandatory separate field when a checkbox is selected

As a designer with limited coding skills, I have developed an acrobat form that includes several due date fields. These fields are only mandatory if a specific checkbox is selected. I am looking for the javascript code that will validate the requirement: ...

Invoking a greasemonkey script when a user interacts with a button

For a script I wrote, I added an extra column and link in each row. However, the issue is that I want the links to trigger a function in my greasemonkey script and pass a variable to it. I have learned that because greasemonkey operates in a sandbox, achi ...

Detecting server errors in Nuxt.js to prevent page rendering crashes: A Vue guide

Unique Context This inquiry pertains to a previous question of mine, which can be found at this link: How to handle apollo client errors crashing page render in Nuxt?. However, I'm isolating the focus of this question solely on Nuxt (excluding apollo ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

Tips for utilizing v-model with props within a v-for loop in Vue 3

I am trying to implement v-model with props inside a v-for loop. I have successfully used v-model with props in the past using computed variables, but I am unsure how to achieve this within a v-for loop. Here is my current code: <script setup> const ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

Encountering a problem while integrating highchartsjs into a Vue3 application

I'm currently using Vue 3 and I followed the documentation to add highchartsjs to my project. However, I encountered an error: ✘ [ERROR] Could not resolve "highcharts" node_modules/highcharts-vue/dist/highcharts-vue.min.js:1:90: 1 │ ... ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...