0

我这样声明状态:

const symbols = reactive( new Map() );

键是动态的(这会隐藏数据库表),symbols.set(id, {...})由 . 添加和删除symbols.delete(id)

我应该如何迭代reactive的键和值?试过这个,我总是得到一个空的迭代器:

    const symbolsByLayer = computed(() => {
      console.debug("New stuff!", symbols);   // This shows '[[Target]]' with two entries

      console.debug( Array.from(symbols.entries()) );   // Array(0)
      console.debug( Array.from(symbols.keys()) );   // Array(0)
      console.debug(Object.entries(symbols));   // Array(0)

我还没有找到提到使用reactive动态键的文档,但我认为它应该是可能的。

4

2 回答 2

0

让它与这个一起工作:

const symbolsSortedByLayer = computed(() => {   // () => [ {...symbolsD, _id: index } ]   // sorted by layer

  const arr = Array.from(symbols.entries(), ([id,o]) => ({ ...o, _id: id }) );    // add '_id' to all entries
  const arr2 = arr.sort( (a,b) => a.layer ?? Number.NEGATIVE_INFINITY - b.layer ?? Number.NEGATIVE_INFINITY );

  console.log("Array of symbols (sorted): ", arr2);
  return arr2;
});

仍然不知道为什么问题中的代码给出了空数组。离开这里,以防有人指出。

于 2020-07-09T21:44:33.567 回答
0

我知道为时已晚,但万一其他人有同样的问题:

reactive在内部用作Proxy对象,因此您不能像与普通对象一样直接与它交互。

您可以使用toRaw函数将反应对象转换回普通对象,以对其执行操作。但请记住,这个“正常对象”会失去反应特性。

于 2021-01-09T22:05:05.813 回答