我在 vuejs 实验中必须面对问题。
我的数据中有两个数组,例如:
columns: [
{ name: "col1" },
{ name: "col2" },
{ name: "col3" },
{ name: "col4" }
],
items: [
{
name: "col1-i1",
id: 1241,
column: "col1"
},
{
name: "col1-i2",
id: 1241242,
column: "col1"
},
{
name: "col2-i1",
id: 1242421,
column: "col2"
}
]
然后我构建由这两个数组组成的对象,如下所示:
computed: {
list() {
return this.columns.map(col => {
return {
column: col,
items: this.items.filter(item => item.column === col.name)
};
});
}
},
在我的列表对象之后,我有这样的结构:
[{
"column": {
"name": "col1"
},
"items": [
{
"name": "col1-i1",
"id": 1241,
"column": "col1"
},
{
"name": "col1-i2",
"id": 1241242,
"column": "col1"
}
]},{
"column": {
"name": "col2"
},
"items": [
{
"name": "col2-i1",
"id": 1242421,
"column": "col2"
}
]},{
"column": {
"name": "col3"
},
"items": []},{
"column": {
"name": "col4"
},
"items": []}]
我尝试在 4 列中制作可拖动项目,因此:
<div class="column" v-for="(column, index) in list" :key="index">
{{column.column.name}}
<draggable group="a" :list="column.items">
<div class="item" v-for="item in column.items" :key="item.id">{{item.name}}</div>
</draggable>
</div>
</div>
但它没有被拖到其他列中。
怎么让它向右移动。
示例在这里https://codesandbox.io/s/elated-aryabhata-uslwb?fontsize=14&hidenavigation=1&theme=dark
该问题是由于列表对象在更改时重新计算并且最终得到初始对象而引起的,因为用于生成它的数据(列和项)没有更改。
默认情况下,计算属性仅是 getter,并且它们仅返回计算值。如果要设置计算值,则必须定义一个设置器,并更改列和项目的初始值。
但是,对于这个用例,您应该在安装的钩子中生成列表对象,然后将其提供给可拖动组件。
data: () => ({
list: [],
columns: [...], // your columns
items: [...] // your items
})
mounted(){
this.list = this.columns.map(col => {
return {
column: col,
items: this.items.filter(item => item.column === col.name)
};
});
}
如果您计划动态更新列和项目,那么您应该为这些属性定义一个观察器,并重新计算列表。
是的,它几乎可以工作,但我有一个小问题,我的数据(列和项目)从 vuex 获取,computed: { ...mapGetters({ columns: 'columns', items: 'items' }) },所以在安装中我在列和项目中没有数据,除了安装方法中的 setTimeout 之外,还有其他解决方案吗