You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vue-draggable无法直接修改Props数组的技术问题咨询

Hey there! That warning pops up because Vue enforces a one-way data flow—props are meant to be passed down from parent to child, and children shouldn’t mutate them directly. Let’s fix this with vue-draggable while keeping things Vue-friendly.

Solution 1: Use a Local Data Copy + Watcher

Create a local copy of the prop in your child component, sync it with the parent’s value via a watcher, and emit an event whenever drag changes happen to update the parent’s array.

Child Component Code:

<template>
  <draggable v-model="localArray" @change="onDragUpdate">
    <div v-for="item in localArray" :key="item.text">
      {{ item.text }}
    </div>
  </draggable>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: { draggable },
  props: ['array1'],
  data() {
    return {
      // Make a shallow copy of the prop to avoid direct mutation
      localArray: [...this.array1]
    };
  },
  watch: {
    // Sync local copy if parent's array changes
    array1(newValue) {
      this.localArray = [...newValue];
    }
  },
  methods: {
    onDragUpdate() {
      // Emit an event to tell the parent to update the original array
      this.$emit('update:array1', [...this.localArray]);
    }
  }
};
</script>

Parent Component Usage:
Use v-model to automatically handle the update event (Vue recognizes update:propName as the default event for v-model):

<child-component v-model="array1" />

Solution 2: Use a Computed Property with Getter/Setter

A cleaner approach is to use a computed property that acts as a bridge between the prop and the draggable component. The getter returns a copy of the prop, and the setter emits an event to update the parent.

Child Component Code:

<template>
  <draggable v-model="syncArray">
    <div v-for="item in syncArray" :key="item.text">
      {{ item.text }}
    </div>
  </draggable>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: { draggable },
  props: ['array1'],
  computed: {
    syncArray: {
      get() {
        // Return a copy of the prop to avoid direct mutation
        return [...this.array1];
      },
      set(newValue) {
        // Emit event to update parent's array
        this.$emit('update:array1', newValue);
      }
    }
  }
};
</script>

Parent Component Usage:
Same as above—just use v-model to bind the array:

<child-component v-model="array1" />

Both approaches follow Vue’s one-way data flow rules: the child never modifies the prop directly. Instead, it works with a local copy and tells the parent to update the original data via events. This keeps your data flow predictable and eliminates that warning.

内容的提问来源于stack exchange,提问作者gileneusz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:22:35