Home > OS >  How to change several data items to true one at a time in Vuejs
How to change several data items to true one at a time in Vuejs

Time:11-04

I am very new to Vuejs and I am wondering how I can make this work in Vuejs

I have a set of different data:

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

And when I click on a button it invokes openOptions() and it changes a specific property to true or false.

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

However, I can't have 2 properties being true. I need to set everything else to false but I am having a hard time understanding how I can make this work. So basically what I need is

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

Can anyone help me with that?

CodePudding user response:

You can first create an object as a single entity, I've used an object with name as collection

Live Demo

Codesandbox Demo

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

then, you can attach click listener on each elment(if you want, you can also attach a single click listener on its parent)

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

when user click on any button then only its value will set to true and rest others are false as:

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