首页 > 解决方案 > 使用带有 Typescript 的计算属性对数组进行排序时出现问题

问题描述

我正在尝试在打字稿单页应用程序中使用 Vue,其中一系列数组需要显示在屏幕上的列表中,但需要显示排序。似乎是一个简单直接的问题,但我所举的例子似乎都没有在 Typescript 中工作。有人可以给我一个工作示例,说明如何让打字稿从 Vue 数据中的数组中接受 Vue 计算函数?

我在 Vue 配置中创建了一个 orderedRegions 计算函数。这应该返回一个名为“Regions”的 Vue 数据对象的排序版本。预期的结果是 ordredRegions 将返回按字母顺序排序的相同列表。

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

我已经确定,如果我去掉打字稿部分,并将其插入到我编译的 javascript 文件中,它确实可以工作,但打字稿将无法编译,因为“this.Regions”对象显示为不存在的错误。看来 Visual Studio Code 中的 Typescript 期望“this”指代函数范围,而不是 Vue 范围。

关于如何让 Typescript 对此感到满意的任何想法?

..基于反馈的其他尝试:1)我尝试使用“速记”,如下所示,但似乎有相同的结果。“this”指的是函数,而不是 Vue,Typescript 给出错误:“类型 '{ sortedRegions: () => any;orderedRegions(): Region[]; } 上不存在属性 'Regions'”

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

2)我也尝试过箭头功能,同样来自 Typescript 的错误:

orderedRegions: () => {
    function compare(x : Region, y: Region) {
        if (x.name < y.name) {
            return -1;
        }
            if (x.name > y.name) {
            return 1;
        }
            return 0;
    }
    return this.Regions.sort(compare);
}

标签: typescriptvue.js

解决方案


那么对于我的打字稿项目,我使用基于类的 api。如果你使用基于类的 api,你可以有一个get functionwhich order 列表。getter 被识别为计算函数。

<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>


推荐阅读