【问题标题】:Is there a better way to write this code in svelte using dexie?有没有更好的方法可以使用 dexie 在 svelte 中编写此代码?
【发布时间】:2021-11-29 18:24:12
【问题描述】:

尝试学习 svelte 并使用 dexie。有没有更好的方法从 indexedDB 获取数据到数组中?

我的functions.js文件

export const db = new Dexie("todos");

db.version(1).stores({
  todo: "++id,note",
});

App.svelte

<script>
  import { onMount } from "svelte";
  import { db } from "./functions";

  let newnote = "";
  let addnote = (e) => {
    db.todo.add({ note: newnote });
    db.todo.toArray().then(items => {
      todos = items;
    });
  };

  $:todos = [];
  let start = () => {
    db.todo.toArray().then(items => {
      todos = items;
    });
  };

  onMount(() => {
    start();
  });
</script>

<main>
  <h1 id="title">ToDo</h1>
  <input type="text" id="newnote" bind:value={newnote} />
  <input type="button" value="Add" on:click={addnote} />

  <br>
  {#each todos as todo}
    {todo.note} <br>
  {/each}
</main>

顺便说一句,你能把这段代码隐藏在应用程序中吗?如果是这样,怎么做?还是没有必要?

【问题讨论】:

    标签: svelte dexie


    【解决方案1】:

    使用来自 dexie@3.2.0 的新 liveQuery(),您将获得最简单的集成。

    npm install dexie@latest
    

    在下面的代码框里玩这个:https://codesandbox.io/s/svelte-with-dexie-livequery-2n8bd?file=/App.svelte

    翻译你的具体例子:

    <script>
      import { liveQuery } from "dexie";
      import { db } from "./functions";
    
      let newnote = "";
      let addnote = (e) => {
        db.todo.add({ note: newnote });
      };
    
      const todos = liveQuery(
        () => db.todo.toArray()
      );
    </script>
    
    <main>
      <h1 id="title">ToDo</h1>
      <input type="text" id="newnote" bind:value={newnote} />
      <input type="button" value="Add" on:click={addnote} />
    
      <br>
      {#if $todos}
        {#each $todos as todo}
          {todo.note} <br>
        {/each}
      {/if}
    </main>
    
    

    一些解释:

    • Dexie 的 liveQuery() 返回一个与 rxjs 兼容的 observable、es-observable 提案以及Svelte's store contract)
    • 初始结果是未定义的(这就是我们需要#if todos 的原因),因为结果是异步的。
    • 当您改变数据库时,您不需要关心重新查询 - 这会自动发生。
    • 即使数据库从另一个选项卡或窗口发生变化,您的视图也会更新。
    • 您的查询可以根据需要变得简单或复杂。它甚至可以是一个异步函数,连续等待多个查询并返回最终结果。它将观察它查询的所有内容,并且每当数据库以一种会影响所涉及的任何查询的方式发生变异时,将重新执行整个函数。观察是细粒度的以优化性能。例如,如果您查询所有带有特定标签的 todoItems (db.todo.where({tags: 'sports'})),假设标签是一个多条目 intexed 数组,除非更新、添加或删除带有该标签的 todoItem ,或者如果另一个 todoItem 获得了“sports”标签。

    我有 blogged about this feature 以及它如何增强 ReactJS 应用程序,但是,直到最近我才知道 Svelte 商店合同,并且很高兴地了解到我们可以免费集成 Svelte。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2013-01-14
      • 2017-08-19
      • 2020-03-14
      • 1970-01-01
      相关资源
      最近更新 更多