【问题标题】:Change property before window.confirm()在 window.confirm() 之前更改属性
【发布时间】:2019-02-03 22:55:15
【问题描述】:

下面是我的代码:

<a
  @click="destroy"
  :class="['button', { 'is-loading': deleting }]"
>
  Delete
</a>

data: () => ({
  deleting: false
}),
destroy () {
  this.deleting = true

  if (!confirm('Sure?') {
    this.deleting = false
    return
  }
}

结果显示一个模态对话框和this.deleting is not true:/

是否可以在对话框之前更改删除属性?

【问题讨论】:

  • 你能发一个minimal reproducible example吗?
  • this.deleting is not true 是什么意思。当时confirm 被调用并且模态显示this.deleting 为真。但是,如果您希望 vue 组件执行一些不同的渲染,因为您更改了 this.deleting,那么这不会发生,因为 confirm 正在阻塞。

标签: javascript vue.js


【解决方案1】:

在确认对话框出现时,用户界面似乎尚未更新。您可以使用 setTimeout(func, 0) 稍微延迟确认对话框,以确保 UI 已更新。

它应该类似于:

destroy () {
  this.deleting = true

  // Store reference to `this` for access during callback.
  var self = this;

  setTimeout(function() {
      if (!confirm('Sure?') {
        // self - refers to `this` in the outer context.
        self.deleting = false
        return
      }
  }, 0);
}

destroy () {
  this.deleting = true

  setTimeout(() => {
      if (!confirm('Sure?') {
        this.deleting = false
        return
      }
  }, 0);
}

requestAnimationFrame 也可能是一个不错的选择。

见:How to tell when a dynamically created element has rendered

注意:我没有对此进行测试,因为您的问题中没有 MCVE。

【讨论】:

  • 解释很可能是正确的,但是超时回调中的this 现在引用了错误的元素。
  • @t.niese 好收获!谢谢。我会更新答案。
  • 顺便你可以写 setTimeout(() => { this... }
  • @nrkz 是的,在这种情况下,这将是一个更好的选择。
【解决方案2】:

当时confirm 被调用并且模态显示this.deletingtrue。但是如果你期望 vue 组件做一些不同的渲染,因为你改变了this.deleting,那么这不会发生,因为确认是阻塞的。

我建议将confirmalertprompt 的本机对话框处理包装到自己的函数中。这不仅允许它们被异步打开/触发,而且还可以在以后用自定义对话框替换它们。

使用 await/async 和 Promises 有一个很好的方法来做到这一点:

你的对话模块

const dlgs = {}

dlgs.confirm = function (message) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(confirm(message))
    },0)
  })
}

你的 vue 组件

<a
  @click="destroy"
  :class="['button', { 'is-loading': deleting }]"
>
  Delete
</a>


data: () => ({
  deleting: false
}),
async destroy () {
  this.deleting = true

  if (! await dlgs.confirm('Sure?') {
    this.deleting = false
    return
  }

  // do the deleting
}

拥有使用 html 实现的自定义对话框,其优点是您可以在打开对话框时在后台更新信息。

【讨论】:

  • 感谢您的回答。对我来说,这样的事情已经过时了;)毕竟我不会使用确认方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多