我有一個非常有趣的問題。我有一個來自 Graphql 的資料。我想在陣列中的陣列中添加一個物件。
但我做不到。我有一個錯誤是物件不可擴展。
讓我舉一個我的資料的例子:
{
"data": {
"board": {
"id": "1",
"title": "Grocieries",
"color": "teal",
"lists": [
{
"id": "1",
"title": "To-Do",
"cards": [
{
"id": "1",
"title": "Write novel"
},
{
"id": "2",
"title": "Buy food"
},
{
"id": "3",
"title": "Paint a picture"
}
]
},
{
"id": "2",
"title": "In progress",
"cards": [
{
"id": "4",
"title": "Buy groceries"
},
{
"id": "5",
"title": "Pay the bills"
},
{
"id": "6",
"title": "Get the car fixed"
},
{
"id": "7",
"title": "Create a course"
}
]
},
{
"id": "3",
"title": "Done",
"cards": [
{
"id": "8",
"title": "Get the car fixed"
},
{
"id": "9",
"title": "Write novel"
},
{
"id": "30",
"title": "Buy fruits"
},
{
"id": "31",
"title": "Buy car"
}
]
}
]
}
}
}
讓我解釋一下我想要做什么:
我想在卡片陣列中添加一個物件,該物件位于 ID 為 1 的串列項內。
實際上,以編程方式進行并不難。但我有那個錯誤:
錯誤影像
我的代碼:
<script>
import CardAdd from '../graphql/mutations/CardAdd';
import BoardQuery from '../graphql/queries/BoardWithListsAndCards';
export default {
methods: {
cardAdd(){
this.$apollo.mutate({
mutation: CardAdd,
variables: {
title: "Mutation added",
order: 1,
listId: 1,
ownerId: 1
},
update(store, { data: { cardAdd } }){
let data = store.readQuery({
query: BoardQuery,
variables: {
id: 1
}
});
data.board.lists.find(list => list.id == 1).cards.push(cardAdd);
}
});
}
}
}
</script>
注意:cardAdd 是我想在卡片陣列中添加的物件。
我也嘗試用索引添加。
謝謝你
uj5u.com熱心網友回復:
data在嘗試推送之前制作一份副本。
let data = store.readQuery({
query: BoardQuery,
variables: { id: 1 }
});
let data2 = JSON.parse(JSON.stringify(data2)); // deep copy
data2.board.lists.find(list => list.id == 1).cards.push(cardAdd);
TBH 不過,這種方法是一個不好的方向。您正在改變一些資料,然后改變從突變回傳的值。你的變異應該回傳你需要的資料,然后你應該能夠直接使用它。
uj5u.com熱心網友回復:
讓我分享幫助他人的最終解決方案:
let data = store.readQuery({
query: BoardQuery,
variables: {
id: 1
}
});
let data2 = JSON.parse(JSON.stringify(data));
data2.board.lists.find(list => list.id == 1).cards.push(cardAdd);
store.writeQuery({ query: BoardQuery, data: data2 });
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520842.html
