Vue3使用draggable嵌套可拖拽元素时防止多选选项重复的方案咨询
问题根因
所有多选题共用了全局定义的multipleChoiceList数组作为选项数据源,对该数组的任何修改都会同步到所有多选题的渲染结果里,自然会出现新增选项同步到所有题目的问题。
修复步骤
1. 调整克隆逻辑,给每个多选题新增独立的选项存储
修改cloneItem方法,当克隆的是多选题类型时,给返回的题目对象新增专属的choices数组存储当前题的选项:
cloneItem({ id, name, type }) { const newItem = { name: name, id: Math.ceil(Math.random()*1000), // 加大随机范围避免ID重复 text: "", type: type, }; // 多选题默认自带2个空选项,可根据需求调整 if (name === 'Multiple Choice') { newItem.choices = [ {text: "选项1", type:"choice"}, {text: "选项2", type:"choice"} ] } return newItem; }
原来的全局multipleChoiceList可以直接删除,不需要再使用。
2. 修改多选题模板的数据源绑定
把多选题区域draggable组件绑定的list从全局multipleChoiceList改成当前题目自己的choices数组:
<draggable class="p-2 rounded-md w-full" :list="element.choices" <!-- 修改此处数据源 --> :group="{ name: 'choice-' + element.id, pull: false, put: false, sort: true }" <!-- group名加题目ID避免拖拽跨题干扰 --> sort: true handle=".handle" @change="log" item-key="id" <!-- 建议后续给每个选项也加唯一ID,避免渲染异常 --> >
3. 调整新增选项逻辑
修改addChoice方法,新增选项仅插入当前操作题目的专属choices数组:
addChoice(questionId) { // 找到当前操作的多选题对象 const targetQuestion = this.questionsList.find(item => item.id === questionId) if (targetQuestion) { targetQuestion.choices.push({ text: "选项" + (targetQuestion.choices.length + 1), type: "choice" }) } }
4. 补充选项删除逻辑
原来的remove方法是删除整道题,要给选项删除单独新增方法:
首先修改选项删除按钮的点击事件:
<div @click="removeChoice(element.id, index)"> <i class="las la-trash-alt text-red-800 la-1x cursor-pointer"></i> </div>
新增removeChoice方法:
removeChoice(questionId, choiceIndex) { const targetQuestion = this.questionsList.find(item => item.id === questionId) if (targetQuestion) { targetQuestion.choices.splice(choiceIndex, 1) } }
内容的提问来源于stack exchange,提问作者Eric.18
相关产品推荐
相关产品推荐

