lrembacz / vue-responsive-grid-layout

Vue Repsonsive Grid Layout
MIT License
83 stars 19 forks source link

Cannot add and remove child #14

Closed kevinsamyn closed 5 years ago

kevinsamyn commented 5 years ago

How can I add and remove child dynamicaly ? Thanks for your job.

lrembacz commented 5 years ago

You should insert new item into all breakpoints arrays inside layouts object if you want to add an item. Or just delete it when you want to remove this item.

AddItem method can be like so:

addItem() {
    const max = this.layouts[this.breakpoint]
        .reduce(
            (max, item) => parseInt(item.i) > max ? parseInt(item.i) : max,
            0
        );
    const newId = max + 1;
    Object.keys(this.layouts).map( breakpoint => {
        this.layouts[breakpoint].push({
            x: 0,
            y: 0,
            w: 2,
            h: 2,
            i: newId.toString()
        })
    });
}

And remove should be similar, just find index of item you want to remove and just splice it.

You just need to remember about reactivity caveats. https://vuejs.org/v2/guide/reactivity.html https://vuejs.org/v2/guide/list.html#Caveats

mateuszlewko commented 5 years ago

Following code for remove doesn't work. After deleting some child and adding new one later (with different id), old child reappears through onLayoutInit.

Object.keys(this.layouts).map(breakpoint => {
      let index = this.layouts[breakpoint].findIndex(item => item.i === id);
      if (index !== -1) {
        this.layouts[breakpoint].splice(index, 1);
      }
    });

onLayoutInit:

onLayoutInit(layout, layouts, cols, breakpoint) {
    console.log(`init curr layout: ${JSON.stringify(this.layouts)}`);
    console.log(`init recv layout: ${JSON.stringify(layout)}`);
    this.cols = cols;
    this.breakpoint = breakpoint;
    this.$set(this.layouts, breakpoint, layout);
  }
mateuszlewko commented 5 years ago

@lrembacz I roughly reviewed the code and I think I know what may be causing this strange behaviour. In these two lines you use slice instead of splice. Slice doesn't modify existing array - just returns new one. https://github.com/lrembacz/vue-responsive-grid-layout/blob/0afa8794ec74805495a8818363c07422f1f3ea8a/src/components/VueResponsiveGridLayout.vue#L307 https://github.com/lrembacz/vue-responsive-grid-layout/blob/0afa8794ec74805495a8818363c07422f1f3ea8a/src/components/VueGridLayout.vue#L472

Changing slice to splice there should fix the issue. slice vs splice

lrembacz commented 5 years ago

Yes, you're right! Thanks! It is already changed in another version :)