gpt4 book ai didi

javascript - 在nedb中添加的记录是单个记录,但是为什么VUE会多次存储相同的记录?

转载 作者:行者123 更新时间:2023-12-03 12:40:21 32 4
gpt4 key购买 nike

我正在Vue中使用 Electron 。我正在使用nedb保存数据。我将事件从vue组件发送到background.js,当它返回数据时,它将以fibbonaccicaly将数据添加到vuex中。
喜欢

  • 如果我添加1个对象,比如说A,然后vuex存储1个对象
  • 如果我再添加1个对象,比如说B,那么vuex商店总共有3个对象
    对象(A代表1个,B代表2个);等等。

  • 所以我只需要一次在vuex中插入数据。我该怎么做?

    //在CreateNewTodo.vue中
    methods:{

    // saveTodo method get triggers when user submit the form in modal

    saveTodo() {
    if (this.isFormValid) {
    const newTodo = {
    task: this.task,
    priority: this.priority,
    eventDate: this.eventDate,
    createdDate: new Date(),
    completedDate: null,
    isCompleted: false,
    };

    // new Todo is an object that contains data that is requested from user
    // from a form like task, priority and eventDate

    ipcRenderer.send('createNewTodo', newTodo);
    ipcRenderer.on('createNewTodoResponse', (e, newDoc) => {
    if (typeof newDoc === 'object') {
    this.$store.dispatch('createNewTodo', newDoc);
    $('#createNewModal').modal('hide');
    } else {
    $('#createNewModal').modal('hide');
    }
    });
    }
    },
    }

    //在background.js中
    ipcMain.on('createNewTodo', (e, args) => {

    // db.performTask is a function that insert document/record in nedb.
    // I've used nedb-promises. In return we'll get promise.

    const dbpromise = db.performTask('todos', 'insert', args);

    // newDoc is the newly inserted document, including its _id

    dbpromise.then((newDoc) => {
    e.sender.send('createNewTodoResponse', newDoc);
    })
    .catch(() => {
    e.sender.send('createNewTodoResponse', 'error');
    });
    });

    //vuex商店
    const state = {
    todos: [],
    };

    const getters = {
    getAllTodos(todosState) {
    return todosState.todos;
    },
    };

    const mutations = {
    CREATE_NEW_TODO(todosState, todo) {
    todosState.todos.push(todo);
    },
    };

    const actions = {
    createNewTodo({ commit }, todo) {
    commit('CREATE_NEW_TODO', todo);
    },
    };

    最佳答案

    每次保存待办事项时,都要为IPC回复 channel 注册一个新的监听器。监听器都保持 Activity 状态,每个监听器都选择并处理每个事件。那不是您想要的,您只想处理每个响应一次,而 Electron 有一种处理方法:)尝试以下一种方法:

        // register a listener to process the response (once)
    ipcRenderer.once('createNewTodoResponse', (e, newDoc) => {
    if (typeof newDoc === 'object') {
    this.$store.dispatch('createNewTodo', newDoc);
    $('#createNewModal').modal('hide');
    } else {
    $('#createNewModal').modal('hide');
    }
    });

    // send the request
    ipcRenderer.send('createNewTodo', newTodo);

    关于javascript - 在nedb中添加的记录是单个记录,但是为什么VUE会多次存储相同的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997076/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com