问题描述
限时送ChatGPT账号..在我的项目中,我有一个包含三个 ul
列表的组件.另外我有一些带有项目的数据数组,每个项目都有一些属性.我的目标是:
我没有复制粘贴大量代码,而是尝试通过在此处使用简单示例来重现 jsfiddle 中的错误行为:
https://jsfiddle/89pL26d2/4/
问题是,当您拖放时,您正好拖动了 2 个项目,而不是一个.
然而,当我从计算属性切换到 watch
时,我得到了想要的行为并且一切正常.
我弄清楚哪一行导致了错误:当我更新 item 属性时的那一行告诉我在拖动完成后该项目应该属于哪个列表.但我不明白为什么会导致这个
我知道这不是直接处理 HTML 的最佳方式,但我现在可以接受.
解决方案一般来说,每当我在 Vue 中看到一个问题,尤其是与列表相关的问题,更新了错误的项目或类似的问题时,它归结为 Vue 试图聪明但会出错,因为它没有最好的信息.这几乎总是可以通过使用 key
来解决.
建议尽可能提供带有 v-for 的密钥,除非迭代的 DOM 内容很简单,或者你是故意的依靠默认行为来提高性能.
密钥.
<div><ul id="listA" data-list="A" class="connectedSortable"><li v-for="item in listAFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li><ul id="listB" data-list="B" class="connectedSortable"><li v-for="item in listBFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
添加密钥解决您的问题.
In my project I have a component with three ul
lists. Also I have some kind of data array with items, each item has some properties. My aim is to:
Instead of copy-pasting a lot of code, I tried to reproduce the incorrect behaviour in jsfiddle by using simple example here:
https://jsfiddle/89pL26d2/4/
The thing is, when you drag&drop, you got exactly 2 items dragged, instead of one.
However, when I switched from computed properties to watch
, I got the desired behaviour and everything worked just fine.
I figure out which line causes the error: the line when I update item property telling me which list the item should belong to after drag is finished. But I can't figure out why it causes this
I know that it's not the best way to work with HTML directly, but I'm okay with that for now.
解决方案Generally, whenever I see an issue in Vue, especially related to lists, where the wrong item is updated or something like that, it comes down to Vue trying to be smart but getting it wrong because it doesn't have the best information. This is almost always solved by using a key
.
It is recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.
Key.
<div id="app">
<div>
<ul id="listA" data-list="A" class="connectedSortable">
<li v-for="item in listAFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
</ul>
<ul id="listB" data-list="B" class="connectedSortable">
<li v-for="item in listBFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
</ul>
</div>
</div>
Adding a key fixes your issue.
这篇关于Vuejs 计算属性和 jquery ui 可排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论