0

There are 2 toggle buttons. If the value is true, then add to the array, otherwise remove the element.

data:

originality: []

toggles:

<toggle id='1' ref='toggleOriginal'> Click </toggle>
<toggle id='2' ref='toggleAnalog'> Click </toggle>

methods:

 if(this.$refs.toggleOriginal.isActive) {
    this.originality.push(this.$refs.toggleOriginal.id);
 } else {
    this.originality = this.originality.filter((item) => {
      return item == this.$refs.toggleOriginal.id;
   });
 }

 if(this.$refs.toggleAnalog.isActive) {
    this.originality.push(this.$refs.toggleAnalog.id);
  } else {
    this.originality = this.originality.filter((item) => {
      return item == this.$refs.toggleAnalog.id;
    });
  }

And the same for the second. In isActive I check for true / false. the problem is that if two toggle is true and I want to convert one to false, then the wrong element is removed. Perhaps you should use a different functionality?

3
  • You can use a v-model to link the toggle's state to a variable (for example it's ID). You can then use a computed value to create the originality array. No need to juggle their values manually. Commented Dec 22, 2021 at 12:09
  • @PeterKrebs Thanks for your replay. I dont think i can use v-model for a component. Is not it? Commented Dec 22, 2021 at 12:15
  • Of course you can use v-model for a component. That is a reason it exists, so you don't have to juggle the value manually between each component. Commented Dec 22, 2021 at 13:05

1 Answer 1

1

To remove from array using filter, you should test for non-equality. Your example uses equality, and that will remove all but your item.

this.originality = this.originality.filter((item) => {
      return item !== this.$refs.toggleOriginal.id;
   });

or splice

const index = this.originality.indexOf(this.$refs.toggleOriginal.id)
this.originality.splice(index, 1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.