Reordering arrays with sort and filter in vuejs

Time:2021-5-31
Problem description
In Vue project, the method of using filter encapsulation to sort arrays has the following probability:

Reordering arrays with sort and filter in vuejs

problem analysis
//Function: use moment to convert date to time stamp, and use sort method of array to sort
filters: {
    sortList: function(v) {
        return v.sort(function(a, b) { 
            return moment(b.startTime).unix() - moment(a.startTime).unix()
        })
    }
 },
In Vue, the change of data caused by the operation of sort method on array will be monitored, which will trigger the filter in filters to recalculate after the change of data, resulting in repeated execution of this process and burst out errors.
Solution
Through the slice method of the array, it makes a shallow copy of the original array, and operates the new array. It will not change the original array, and it will not trigger the data response.
filters: {
    sortList: function(v) {
        return v.slice().sort(function(a, b) { 
            return moment(b.startTime).unix() - moment(a.startTime).unix()
        })
    }
 },

Recommended Today

Vue、Three. JS implementation panorama

1、 First, we need to create a Vue project This paper mainly records the process of building panorama in detail, so building Vue project is not described too much. 2、 Install three js npm install three –save npm install three-trackballcontrols –save npm install three-orbit-controls –save npm i three-obj-mtl-loader –save npm i three-fbx-loader –save npm i […]