<div v-for="(item, index) in groups"
:key="item.id" :id="item.id"
class="group-name">
</div>
我不想根據 ID 更改所有陣列值。只有我想使用 ID 更改的特定位置。
我已經使用 api 呼叫中的以下幾行更改完成了該邏輯,例如
const first = data.groups_with_selected[7];
const second = data.groups_with_selected[20];
data.groups_with_selected.splice(2, 0, first, second);
data.groups_with_selected.splice(9, 1)
data.groups_with_selected.splice(21, 1)
有了這個,我最終想要實作的目標我明白了。但問題是,我不能期望陣列值一直相同。所以我決定根據 ID 重新排列陣列值。
在所有陣列值中,我只想更改(第 7 位到第 2 位)和(第 21 位到第 3 位)。
uj5u.com熱心網友回復:
orderMap 將是您想要的索引結果。
array 將是您的 API 回應。
orderMap使用一個函式來映射查找所需的索引并將其放入我們的sorted陣列中。
const orderMap = ['third', 'second', 'first'];
const array = [{name: 'first'}, {name: 'second'}, {name: 'third'}];
let sorted = orderMap.map(function(sortBy){
return this.find(function(toSort){return toSort.name === sortBy})
}, array)
console.log(sorted);
// as method -> Result is your response Data. OrderMap the map to order by.
sortResultSet(result, orderMap) {
return orderMap.map(function(sortBy){
return this.find(function(toSort){return toSort.name === sortBy})
}, result)
}
uj5u.com熱心網友回復:
您可以撰寫自定義排序函式,以便根據您的需要對它們進行排序。例如:
function Sort(item1, item2){
if (item1.name > item2.name)
return 1;
else if (item1.name < item2.name)
return -1;
else
return 0;
}
然后在陣列上呼叫它
array.sort(Sort);
console.log(array);
如果你愿意,你可以省略函式宣告,只將函式作為引數傳遞。
array.sort(function (item1, item2) {
<same code from above>
});
然后只需將其添加到 Vue 所需的物件中
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346183.html
標籤:javascript Vue.js
