skip to Main Content

I’m trying to add/remove strings from a local data array in a method and my logic always ends up with the array always having only a single string, that being the one passed to the updateIdArr method.

Even if I remove the else // remove portion the push never "ads" to the array. The array only ever has 1 string, the last value pushed.

What am I missing?

data() {
  return {
    idArr: [],
  }
},
methods: {
  updateIdArr(show) {
    if (!this.idArr.includes(show._id)) {
      // add
      this.idArr.push(show._id);
    } else {
      // remove
      this.idArr = this.idArr.filter((id) => id !== show._id);
    }
    console.log(this.idArr); 
    // always has *only* the most recent value
    // e.g. ['01GDKN93GP6Q0QDBVQ3W9BDT6D', __ob__: Observer]
  },
}

    

3

Answers


  1. Chosen as BEST ANSWER

    UPDATE: stupid human error

    Each local data value was in a separate component. I need to emit to the parent and maintain the array there.


  2. Your remove method is not doing anything as, unlike push, filter does not modify the array and instead returns a new one:

    this.idArr = this.idArr.filter((id) => id !== show._id);

    Not sure if that would break whatever this __ob__: Observer thing is doing though, if so you may need to filter it in-place using a for loop or something.

    Login or Signup to reply.
  3. can you try this?

    data() {
          return {
            idArr: [],
          }
        },
        methods: {
          updateIdArr(show) {
            if (!this.idArr.includes(show._id)) {
              // add
              this.idArr.push(show._id);
            }
            var _this = this;
            this.$nextTick(() => {
                        delete _this.idArr[_this.idArr.findIndex(x => x.id === show._id)];
            })
         
          },
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search