Vue.js filters in v-for

I was interested to use filters in vue

I know the calculated one and when I use it, but my question is

I used this code to sort an array of fruits instead of using computed

<li v-for="fruit in fruits.sort() ">{{fruit }}</li>

it starts and I got the result correctly

but the console notified me of an error

[Vue warn]: You may have an infinite update loop in a component render function. 
(found in <MyFilter> at C:\xampp\htdocs\projects\max\___explaning\169_filters_mixins\src\MyFilter.vue)
warn @ VM6599:564
flushSchedulerQueue @ VM6599:2340
(anonymous) @ VM6599:511
nextTickHandler @ VM6599:460

when i removed .sort () the warning disappeared

question: why did this warning appear and is there a way to add .sort () to the v-for array without using calculated values

+4
source share
2 answers

You get an error because you create an infinite loop when called fruit.sort()in an instruction v-for.

fruit.sort() (), Vue , DOM v-for. fruit.sort(), .

:

v-for="fruit in fruits.map(f => f).sort()", , . : 1) fruits.map(f => f) , , fruits, 2) .

:

, (, , , ). .

{
    ...Other component properties...

    methods: {
        sorted(arr) {
            // Return a copy of the sorted array
            return arr.map(e => e).sort()
        }
    }

    ...Other component properties...
}

:

Vue 1.x, (v-for="fruit in fruits | orderBy", ({{ }}) Vue 2.x Vue .

- , , , , lodash orderBy(...).

{
    ...Other component properties...

    computed: {
        sortedFruits() {
            // Return a copy of the sorted array
            return this.fruits.map(f => f).sort()
        }
    }

    ...Other component properties...
}

, .

: , .

+2

, , . , v-for, sort.

+1

Source: https://habr.com/ru/post/1675457/


All Articles