【问题标题】:Vue.js - function not executed when data are updatedVue.js - 更新数据时未执行函数
【发布时间】:2020-10-15 23:22:25
【问题描述】:

我的 vue 组件方法中有此功能代码,如果单击按钮并显示 chrome 通知,它将删除客户数据。

        deleteCustomer(id) {
            console.log('deleting customer:' + id);
            db.customers.delete(id).then( () => {
            console.log('customer '+ id +' deleted!');
            browser.notifications.create('deleted',{
                type: 'basic',
                iconUrl: 'icons/128.png',
                title: 'Data removal',
                message: 'data removed with success!'
            });
            this.viewCustomers();
           });
        },

在函数结束时,我调用了另一个方法,该方法应该调用 dexie.js 实例以在表中显示存储的所有客户数据。安装组件后,viewCustomers 函数可以正常工作,并且表格已正确填充。我需要解决的是数据删除后没有调用该方法并且表没有更新。我该如何解决这个问题,是否有我可以使用的 vue 函数或任何可以解决此问题的代码修改?

【问题讨论】:

标签: javascript vue.js vuejs2 vue-component dexie


【解决方案1】:

正如文档中提到的,Delete items 实际上是一个异步调用,这意味着它在项目被删除之前调用了this.viewCustomers(),因此它似乎不起作用。解决此问题的最简单方法是使用 async/await,例如:

async deleteCustomer(id) {
  console.log('deleting customer:' + id);
  await db.customers.delete(id);
  console.log('customer ' + id + ' deleted!');
  browser.notifications.create('deleted', {...});
  this.viewCustomers();
},

现在,this.viewCustomers 函数将仅在 db.customers.delete() 函数完成后才会被调用,这应该会产生所需的输出。

【讨论】:

  • 我在调用.delete() 函数之后添加了一个then。显示通知但未执行该功能。我将按照您的建议更新代码。感谢您的帮助
  • 请更新您的代码以显示您如何添加thenthen 中的viewCustomers。另外,请解释一下the function isn't executed. 的含义。您的意思是,如果您在 viewCustomers 中放置一个未显示的控制台日志?
  • 测试代码但没有按预期工作,通知停止工作:(
  • @palash 我已经用then 更新了代码。对于函数this.viewCustomers(),我的意思是在数据删除后不会调用该函数,并且表格将始终显示旧数据
  • 您是否尝试过使用debugger 关键字来查看then 回调中发生了什么?
【解决方案2】:

经过一番头疼后,我找到了一个棘手的解决方案,让我能够使用更新后的数据更新表格。我使用了chrome.notifications API 的onClicked 方法,现在一切正常,但我愿意接受有关此问题的所有建议。 这是我在 vue 实例的挂载部分添加的代码:

    mounted() {
        console.log('mounted')
        this.$set(this, 'isActive', true)
        this.viewCustomers()
        browser.notifications.onClosed.addListener( (notificationId) => {
            console.log(notificationId)
            this.customersList = [];
            this.viewCustomers();
        })
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2018-08-08
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多