dragkin
dragkin

Reputation: 89

Vue JS Sort Date with components using Computed Property

I tried to sort the date using computed properties but it didnt work, if i using at methods and remove the slice, then it will sort as expected. I've tried to split the date also but still not working. I am not sure what caused the problem.

Kindly find my code as below.

App

<template>
    <div>
        <h2>Ingredients</h2>
        <ul>
            <li></li>
        </ul>
        <ingredients-list  v-for="(ingredient,index) in ingredients"
            :key="index"
            :index='index'
            :foodName="ingredient.food"
            :foodExpiry="ingredient.expiryDate">
        </ingredients-list>
    </div>
</template>
    
<script>
    export default {
        data(){
            return{
                ingredients:[
                {
                    food:'carrot',
                    expiryDate:'2020-12-12'
                },
                {
                    food:'papaya',
                    expiryDate:'2018-1-15'
                },
                {
                    food:'orange',
                    expiryDate:'2021-10-13'
                },
                {
                    food:'meat',
                    expiryDate:'2019-4-23'
                }]
            }
        },
        computed: {
            sortedItems() {
                return this.ingredients.slice().sort( ( a, b) => {
                    return new Date(a.expiryDate)- new Date(b.expiryDate);
                });
            }
        }
    }
</script>

components

<template>
    <div>
        <h2>{{index}}</h2>
        <h2>Food:{{foodName}}</h2>
        <h2>Expiry:{{foodExpiry}}</h2>
    </div>
</template>
    
<script>
    export default {
        props:['foodName','foodExpiry'],
    }
</script>

Upvotes: 1

Views: 1399

Answers (2)

Abdelillah Aissani
Abdelillah Aissani

Reputation: 3108

Like @Anatoly said

Computed props are never calculated if they are not used at all.

What you should be doing to solve the problem is :

  1. Using slice method instead of splice since it mutates the original array:
sortedItems() {
      return this.ingredients.slice()
             .sort((a, b) => new Date(a.expiryDate)- new Date(b.expiryDate));
}
  1. Loop through the computed property and not the original array:
<ingredients-list  v-for="(ingredient,index) in sortedItems"
            :key="index"
            :index='index'
            :foodName="ingredient.food"
            :foodExpiry="ingredient.expiryDate">
</ingredients-list>

Upvotes: 2

Anatoly
Anatoly

Reputation: 22758

It seems you confused splice with slice. You need slice to get a copy of an array and to sort this copy:

 sortedItems() {
            return this.ingredients.slice().sort( ( a, b) => {
                
                return new Date(a.expiryDate)- new Date(b.expiryDate);
            });
        }

Upvotes: 1

Related Questions