Tips on changing multiple data items to true individually within Vuejs

As a beginner in the realm of Vuejs, I'm facing a challenge and seeking guidance on how to implement a specific functionality in Vuejs. I have various pieces of data which are structured like this:

  data() {
    return {
      recents: false,
      frontend: false,
      backend: false,
      devops: false,
      tutoriais: false,
    };
  },

Whenever a button is clicked, it triggers the openOptions() function and toggles a specific property between true and false as per user interaction.

openOptions(e) {
      const optionClicked = e.target.text.toLowerCase();
      this[optionClicked] = !this[optionClicked];
    },

The catch here is that only one property should be set to true at a given time. In other words, all other properties must be set to false when one is set to true. But figuring out the logic for this has been somewhat perplexing for me. Essentially, what I'm looking for is:

set the one I clicked to true
and the rest to false

Could anyone provide some insight or assistance on achieving this behavior?

Answer №1

To start, begin by creating an object that represents a single entity. In this example, the object is named collection

Experience it live

https://codesandbox.io/s/festive-water-vtufs?file=/src/App.vue

data() {
    return {
      collection: {
        recents: false,
        frontend: false,
        backend: false,
        devops: false,
        tutoriais: false,
      },
    };
  },

Next, you can add a click listener to each element individually (or alternatively, add a single click listener to the parent element)

<button
      v-for="[key, value] in Object.entries(this.collection)"
      :key="key"
      v-on:click="() => openOptions(key)"
    >
      {{ key }}
      {{ value }}
    </button>

When a user clicks on any button, only the clicked button's value will be set to true, while all others are set to false:

openOptions(clickedKey) {
  Object.keys(this.collection).forEach((key) => {
    this.collection[key] = key === clickedKey ? true : false;
  });
},

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

Encountered an issue in a NodeJs/Express Vue CLI3 application where an error was thrown stating "

I have recently started working with NodeJs and I am facing an issue while trying to run a Vue app in production mode with Express. I have been trying to solve this for the past three days with no luck. My Vue app is set up with Vue CLI3 and bootstrap 4. W ...

Encountering issues in parsing JSON for PhoneGap Application

I've been struggling with parsing JSON data for a unique PhoneGap application that is dynamically generated by a localStorage variable. The PHP script is functioning properly, but the JavaScript code seems to be encountering issues when trying to pars ...

Using ThreeJS in an iframe on a mobile device can lead to crashes in the browser due to multiple

I am encountering an issue with my ThreeJS based pages that are included via Iframe into other pages. The problem arises when switching between the two pages with ThreeJS Iframe on a mobile phone (specifically an iPhone 7 with just 1GB RAM). After two or ...

What is preventing my for loop from reaching the initial index in this visually distinct nested array pattern?

Struggling with rearranging letters in a W shape using arrays. My code seemed to go down instead of reaching level 0. Code snippet: const row = totalLevel =>{ let array = [] for(let i =0;i<totalLevel;i++){ array.push([]) } r ...

JQuery not being recognized by MVC4 view

I encountered an issue with my @Html.DropDownList that is supposed to invoke a jquery function, but it seems that the function is not being called. I've attempted the following: $(document).ready(function () { $('.test').change(function ...

Ensure that the default value in the text box remains unchanged until new text is input by utilizing jQuery

Can you please review my code snippet on http://jsfiddle.net/7995m/? The issue I'm facing is that the default text in the text box disappears as soon as it's clicked. What I want is for the default text to remain until the user starts typing. Her ...

Getting command line argument parameters in React can be achieved by utilizing the `process.argv`

Is there a way to retrieve command line argument parameters in React? I currently have a React codebase that is utilizing Webpack. When running the following commands - npm run build -- --configuration=dev or npm run build -- --configuration=qa I need t ...

Exploring angularjs and the concept of variable scoping in relation to

Struggling with variable binding in my angularjs/javascript code for uploading images. Can someone help me out? Here is the snippet of my code: var image_source; $scope.uploadedFile = function(element) { reader.onload = function(event) { image_sourc ...

Vue Apollo Query failing to update local data

I have a unique dilemma with my modal that includes dynamic content rendering using import(). There's a form in the modal filled by a Query, and the initial data displays correctly. However, if I make changes to the data, close the modal, and then reo ...

The jQuery onchange function does not have the ability to limit the input to only

When using the script to sum the input value, everything seems to be working fine. However, I am facing an issue where clicking up and down on the "input#total_selfmark" does not change the value. Additionally, when I manually type in a number, the "input# ...

Updating the main Vue app's value from a Vuetify component in Vue - a step-by-step

I have two vue files, app.vue and logincomponent.vue. In logincomponent.vue, I created a template for a login box that communicates with the go backend in Wails. The code is working fine, but I am struggling to change the value in the main app.vue file. ...

Ways to extract information from a text

I have a massive string, divided into two parts that follow this pattern: {\"Query\":\"blabla"\",\"Subject\":\"gagaga"}", {\"Query\":\"lalala"\",\"Subject\":\"rarara&bso ...

Is there a way to utilize a Javascript function to incorporate commas into a div tag?

Being new to JavaScript, I have heard about jQuery but I don't know how to use it. Please bear with me as I am not well-versed in this area. :) I am currently importing data dynamically from an Excel database to a website. Everything is working fine ...

Switch all occurrences of https URLs with <a> using the stencil technology

I am encountering an issue with replacing the answer retrieved from an API and formatting it correctly answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com &bso ...

Scalable Vector Graphics Form Field

I'm looking to enable user input in one of my SVG text fields when they click on it. Any ideas on how to achieve this? const wrapper = document.getElementById('wrapper'); const text = document.getEl ...

Alter the Header/Navigation to switch colors depending on the section of the website currently being viewed

I'm currently revamping my personal portfolio website and had an idea for a cool feature. I want the header/navigation bar to change color based on which section of the webpage it's in (the site is one page only). My initial thought was to add o ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...

Utilize ng-checked in AngularJS to bind all values from an array to checkboxes

I'm working on a project where I need to bind the name and age of a person using checkboxes, with the data looped through ng-repeat. However, I seem to be able to only get the "name" from the array, not the "age". Can someone please help me find my mi ...

What is the best way to implement Redux within Next.js 13?

Currently, I am using Next JS 13 with Redux. In Next.js 12, I was able to wrap my entire application with Provider inside ./pages/_app. However, how can I achieve this in Next JS 13? Here is the code from my layout.js: import "../styles/globals.css&q ...

Incorporate a SharpSpring form within a custom React component

Trying to integrate a Sharpspring form script into my React component (page.jsx). The form needs to be placed outside the <head></head> element and inside the <div> where I want to display it. The original HTML code for embedding the for ...