Search code examples
javascriptvue.jsvue.draggable

Vue.js - Child components are re-rendered while updating their position


I'm new to Vue.js and i'm using it alongside with Vue-Draggable in order to re-arrange the position of stand-alone widgets (components) inside the DOM.

I also want to be able to rearrange this position dynamically via an Ajax response containing the order.

The problem that i have with my current implementation is that when i'm re-arranging, the components are re-rendered. I don't want that.

Any ideas would be helpful.

<template>
  <draggable tag="div"
             class="container-fluid"
             @start="drag=true"
             @end="drag=false"
             handle=".v-drag-handle"
             v-bind="dragOptions"
             v-model="widgetList"
  >
    <transition-group type="transition">
      <component v-for="(widget, key) in widgetList"
                 :key="key"
                 :is="widget.widget">
      </component>
    </transition-group>
  </draggable>
</template>


 const widgets = [
    Component1,
    Component2,
    Component3,
    Component4,
    Component5
  ];

  export default {
    name: 'Stack overflow',

    data() {
      return {
        widgetList: [],
        drag: false,
        config: this.getHttpConfig(),
      };
    },

    computed: {
      dragOptions() {
        return {
          animation: 800,
          disabled: false,
          ghostClass: "v-ghost"
        };
      }
    },
    created() {
      this.getWidgetOrder();
    },
    watch: {
      widgetList(val, oldVal) {
        if (oldVal) {
          this.setWidgetOrder(this.widgetList);
        }
      }
    },
    methods: {
      sort() {
        this.widgetList = widgets.map((widget, index) => {
          return { widget: widgets[index], order: index + 1 };
        });
      },
      getWidgetOrder() {
        this.prepareFormData('get');

        this.$http(this.config)
          .then(response => {
            //todo handle response
            this.sort();
          })
          .catch(response => {
            throw new Error('Could not get widget order.');
          });
      }
    },
    components: {
      Component1,
      Component2,
      Component3,
      Component4,
      Component5
    }
}

For time saving i have removed all non-related methods and i kept only the ones that are used while the problem is occurs. I believe that the problem is happening on the v-model, when the widgetList is updated i'm getting this issue.


Solution

  • The problem here occurs because the key in the loop is changing, and Vue automatically re-creates the component.

    The solution was to use the component's name as a key. :key="widget.name"