对象,nuxt,vue js的已过滤数组

时间:2019-08-29 07:45:55

标签: arrays typescript vue.js

我需要根据对象中某个键的值过滤一个数组,但出现错误:

Property 'sort' does not exist on type 'Object'

我希望如果panel.sorttrue,则将呈现数组worktop。否则,将渲染数组groupA

我在做什么错?为什么我的sort键不可见?

export default class PanelSettings extends Vue {
  panels: Array < Object > = [{
      id: 0,
      name: "one",
      sort: true
    },
    {
      id: 1,
      name: "two",
      sort: true
    },
    {
      id: 2,
      name: "three",
      sort: true
    },
    {
      id: 3,
      name: "four",
      sort: true
    },
    {
      id: 4,
      name: "five",
      sort: true
    },
    {
      id: 5,
      name: "six",
      sort: true
    },
    {
      id: 6,
      name: "seven",
      sort: false
    },
    {
      id: 7,
      name: "eight",
      sort: false
    },
    {
      id: 8,
      name: "nine",
      sort: false
    },
    {
      id: 9,
      name: "ten",
      sort: false
    },
    {
      id: 10,
      name: "eleven",
      sort: false
    }
  ];

  get worktop() {
    return this.panels.filter(function(panel) {
      return panel.sort == true;
    });
  };
  get groupA() {
    return this.panels.filter(function(panel) {
      return panel.sort == false;
    });
  };

}
<ul>
  <li v-for="panel in worktop" :key="panel.id" class="mb-3 mr-8">
    <div>
      <tw-pannel class="text-danger button">
        <tw-icon name="minus" />
        <span>{{panel.name}}</span>
      </tw-pannel>
    </div>
  </li>
</ul>
<ul>
  <li v-for="panel in groupA" :key="panel.id" class="mb-3 mr-8">
    <div>
      <tw-pannel class="text-primary">
        <tw-icon name="plus" />
        <span>{{panel.name}}</span>
      </tw-pannel>
    </div>
  </li>
</ul>

2 个答案:

答案 0 :(得分:0)

根据docs,您不应使用Object类型,而应使用object。但是即使那样,sort也不是object的属性,因为javascript的Object没有属性sort

创建界面或键入别名(请参见differences)并使用它代替Object

interface MyPanelObject {
    id: number,
    name: string,
    sort: boolean
}

/*OR:*/

type MyPanelObject = {
    id: number,
    name: string,
    sort: boolean
}

/* change this line: */
panels: Array<MyPanelObject> = [/*panels*/];

答案 1 :(得分:0)

尽管您可以为panels声明适当的类型注释,但实际上在特定的用例中(实际上至少从问题中所显示的)不需要

您可以简单地删除类型注释,并允许TypeScript推断数组类型而不会损失类型安全性:

screencast