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

How to use jQuery to select an element by using 'this' on a button

I have a total of 5 divs, each containing 5 different texts. <div class="text"> <%= theComment.text %> </div> I am working with node.js, MongoDB, and Mongoose. In addition to the divs, I also have a button labeled EDIT with a cl ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

The issue arises with Vue.http.get when using authorization, leading to two failed requests specifically on iOS

I am facing an issue with making authenticated HTTP requests using a bearer token. While it works perfectly fine on most platforms, I have noticed that certain iOS devices are experiencing a problem. fetchWithToken : function( endpoint, token ){ ret ...

Choosing a box will cause a dashed rectangle to appear when the mouse is selected

Whenever I try to select an option in my select box, a dotted rectangle appears. How do I remove this feature? I have noticed that many others are also facing the same issue. I tried updating my CSS with some properties based on their suggestions, but it ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

Upon receiving the ajax request, the entire code page is called back

I'm having trouble saving data using a button in Laravel. When I use console.log, the entire code appears in the console and I don't understand why this is happening. Here is my input field and button: <form action="{{ url('sendcom& ...

Tips and techniques for implementing push notifications in front-end applications without the need for a page refresh

I am working on a Python program that inserts data into a XAMPP database. I am looking for a way to continuously monitor the database for any changes and automatically send updates to the frontend without relying on click events. Is there a method simila ...

Angular ng-bind is incorrectly displaying the value as 'object' instead of the intended value

I am working on an Angular app where I am retrieving data from a service in the following manner: angular.module('jsonService', ['ngResource']) .factory('MyService',function($http) { return { getItems: ...

retrieving embedded content from an iframe on Internet Explorer version 7

Need help with iframe content retrieval $('.theiframe').load(function(){ var content = $(this.contentDocument).find('pre').html(); } I'm facing an issue where the iframe content is retrieved properly in FF, Chrome, and IE 8,9 ...

Tips for implementing a shape divider in vuetify.js

Currently, I am incorporating the vuetify library into my project and attempting to include a shape divider similar to the one displayed in the image below. Unfortunately, I have been unsuccessful in achieving this desired effect. https://i.stack.imgur.c ...

"Learn to easily create a button within a table using the powerful functionality of the dataTable

I need to add a button to each row in a table. I managed to achieve this with the code below, but there's a problem - every time I switch between pages, the button keeps getting added again and again. It seems like the button is generated multiple tim ...

Encounter a problem while installing node modules

I am facing an issue with my test directory which contains a package.json file: { "name": "test", "version": "0.0.1", "dependencies": { "hem": "~0.1.6", } } Upon trying to run node install, I encounter the following error: module.js:337 ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

Send form information using AJAX response

I have successfully implemented a feature where I load an iframe into a div with the id of #output using AJAX. This allows me to play videos on my website. jQuery( document ).ready( function( $ ) { $( '.play_next' ).on('click', fun ...

Developing an if-else statement to showcase a different div depending on the URL

Having trouble with an if/else statement to display one div or another based on the URL: No matter what I try, only "Div 1" keeps showing. Here's my code snippet: <script> if (window.location.href.indexOf("pink") > -1) { document.getElemen ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Utilizing Material-UI List components within a Card component triggers all onClick events when the main expand function is activated

Need help with Material-UI, Meteor, and React I am trying to nest a drop down list with onTouchTap (or onClick) functions inside of a card component. While everything renders fine initially, I face an issue where all the onTouchTap events in the list tri ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...