我在 VueJS 中自动保存数据时遇到问题,当我更改当前注释时,自动保存未完成

问题描述 投票:0回答:1

所以我的应用程序遇到了这个问题。我不确定实现此自动保存功能的正确方法是什么。当您更改注释的标题或其内容时,有一个去抖动功能会在 2 秒内关闭,如果您在去抖动更新完成之前更改为当前注释,则它永远不会更新。 如果我解释得不好或者有什么需要澄清的地方请告诉我,谢谢!

这是发生的情况的视频:https://www.loom.com/share/ef5188eec3304b94b05960f403703429

以下是重要的方法:

    updateNoteTitle(e) {
      this.noteData.title = e.target.innerText;
      this.debouncedUpdate();
    },
    updateNoteContent(e) {
      this.noteData.content = e;
      this.debouncedUpdate();
    },
    debouncedUpdate: debounce(function () {
      this.handleUpdateNote();
    }, 2000),
    async handleUpdateNote() {
      this.state = "loading";
      
      try {
        await usersCollection
          .doc(this.userId)
          .collection("notes")
          .doc(this.selectedNote.id)
          .update(this.noteData)
          .then(() => this.setStateToSaved());
      } catch (error) {
        this.state = "error";
        this.error = error;
      }
    },
    setStateToSaved() {
      this.state = "saved";
    },
firebase vue.js google-cloud-firestore autosave
1个回答
1
投票

为什么每两秒运行一次?

要自动保存注释,我建议您在窗口关闭或更改选项卡事件时添加事件监听器,就像提供的视频中一样(无论什么事件最适合您)

created () {    
        window.addEventListener('beforeunload', this.updateNote)  
    }

您的

updateNote
函数不是异步的。

但是如果你真的想节省每次更改的费用。 您可以创建一个如下所示的计算属性:

   note: {
      get() {
        return this.noteData.title;
      },
      set(value) {
        this.noteData.title = value;
        this.state= 'loading'
        usersCollection.doc(this.userId)
                       .collection("notes")
                       .doc(this.selectedNote.id)
                       .update(this.noteData)
                       .then(() => this.setStateToSaved());
      }
    },

并将

v-model="note"
添加到您的输入中。 想象一下用户每秒输入 10 个字符,即 10 次调用意味着 10 次保存

编辑:

添加一个名为 isSaved 的属性。 在注释更改上单击

if(isSaved === false)
调用您的
handleUpdateNote
函数。

updateNoteTitle(e) {
  this.noteData.title = e.target.innerText;
  this.isSaved = false;
  this.debouncedUpdate();
}

并在您的函数中

setStateToSaved
添加
this.isSaved = true ;
我不知道你的侧边栏是否是不同的组件。 如果是,并且您使用
$emit
来处理注释更改,则将事件侦听器与 isSaved 属性结合使用。

© www.soinside.com 2019 - 2024. All rights reserved.