typescript - 使用带有 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);
}
解决方案
那么对于我的打字稿项目,我使用基于类的 api。如果你使用基于类的 api,你可以有一个get function
which 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>
推荐阅读
- google-apps-script - 如何使用社区可视化 - 桑基图?
- python - 如何在 Python 中按最大日期分组
- aws-documentdb-mongoapi - 从 mongoDB 迁移后的 AWS DocumentDB 错误
- html - 是否可以使用 Puppeteer 将 PDF 转换为 HTML?
- python - Emacs org-mode 源代码块被错误地解析为导出中的链接(无法解析链接)
- flutter - 将提供程序包添加到 Flutter Web 项目时出错
- c# - 属性路由与传统表单参数一起使用的问题
- angular - 尝试运行 Angular 8 应用程序时出现“未捕获的错误:预期的‘样式’是字符串数组”
- python - 模式弹出窗口上的单击按钮在 Selenium Python 中给我一个错误
- r - 将样本大小 (n) 添加到每个方面散点图 (R, ggpubr)