vue.jsdragula

Why can't I use dragula in Vue3 setup but mounted?


When I use dragula in vue3 setup. It isn't working. Like this:

setup() {
    const dragFrom = ref(null);
    const dragTo = ref(null);
    onMounted(() => {
      dragula([dragFrom, dragTo], {
        copy: (el) => {
          console.log(el);
          return true;
        },
        accepts: () => {
          return true;
        },
      });
    });
    return { dragFrom, dragTo };
}

But this way can be successful:

mounted() {
    const dragFrom = this.$refs.dragFrom;
    const dragTo = this.$refs.dragTo;
    dragula([dragFrom, dragTo], {
      copy: function (el, source) {
        console.log(el);
        return true;
      },
      accepts: function (el, target) {
        return true;
      },
    });
}

Both methods are based on vue3.What's wrong?


Solution

  • Your issue comes from the fact that you are not accessing the value of the ref, i.e. dragFrom.value and dragTo.value when passing them into the dragula() function. Remember that when you create a reactive and mutable ref object, you will need to access its inner value using the .value property.

    This should therefore work:

    setup() {
        const dragFrom = ref(null);
        const dragTo = ref(null);
        onMounted(() => {
    
          // Ensure you access the VALUE of the ref!
          dragula([dragFrom.value, dragTo.value], {
            copy: (el) => {
              console.log(el);
              return true;
            },
            accepts: () => {
              return true;
            },
          });
        });
        return { dragFrom, dragTo };
    }
    

    See proof-of-concept on this demo CodeSandbox I've created: https://uwgri.csb.app/