[Vuejs]-Problem using computed property with Typescript to sort array

0👍

Well for my typescript project I use class based api. If you use class based api, you can just have a get function which order the list. The getter get identified as computed function.

<template>
    <div>
        <div v-for="item of orderedList" :key="item" xs3>{{ item }}</div>
    </div>
</template>

<script lang="ts">
/** TODO: This component is very similar than the all orders component
 * We can really merge these 2 components some time in the future
 */
import { Component, Vue, Watch } from "vue-property-decorator";
@Component
export default class List extends Vue {
    private unorderedList = ["zTest", "fTest", "aTest", "gTest"];

    get orderedList() {
        return this.unorderedList.sort();
    }
}
</script>

0👍

You can just pass the regions to the orderedRegions function, then you don’t have the this problem when in the function itself.

orderedRegions(myRegions: Region[]) : Region[] {
    function compare(x : Region, y: Region) {
        if (x.name < y.name) {
            return -1;
        }
        if (x.name > y.name) {
            return 1;
        }
        return 0;
    }
    return myRegions.sort(compare);
}

I have tested this and it works. In fact I have used your sorting function.

It’s also better for testing since you don’t have to worry about the this context.

Leave a comment