Scenario: It is more suitable for the background to return all the data. The front-end does the paging function by itself. If the paging function is done in the background, paging should be considered out of order.
principle:
Loop through the array, and generate a number from 0 to length - 1 in each traversal, which represents the position to be randomly exchanged in this loop. Exchange the number at the current position of
this loop with the number at the random position .
JSON data format:
code:
// 乱序
// this.selectedData 是接口返回的json数据
upsetOrder () {
let arr = deepCopy(this.selectedData)
for (let i = 0, len = arr.length; i < len; i++) {
let random = parseInt(Math.random() * (len - 1));
let current = arr[i];
arr[i] = arr[random];
arr[random] = current;
}
// 乱序后 重置权重
let number = 0
arr.forEach((e, i) => {
e.weight = number += 2
})
this.selectedData = arr
},
Supplementary deepCopy: In order to avoid the situation where the data (this.selectedData) is directly assigned in several places and is prone to problems, use deepCopy to copy it to avoid memory leaks. (If you find it troublesome, you can also assign directly without using deepCopy)
deepcopy.js:
/**
* @file deepcopy
* @authors KevinChan ([email protected])
* @date 2019/4/15 下午6:57:42
*/
function deepCopy (obj, cache = []) {
function find (list, f) {
return list.filter(f)[0]
}
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
const hit = find(cache, c => c.original === obj)
if (hit) {
return hit.copy
}
const copy = Array.isArray(obj) ? [] : {}
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}
export default deepCopy;
use:
You can directly import it on the page that needs to use deepCopy
import deepCopy from '@/utils/deepcopy'