代码之家  ›  专栏  ›  技术社区  ›  b00sted 'snail'

更改前属性窗口.确认()

  •  0
  • b00sted 'snail'  · 技术社区  · 6 年前

    下面是我的代码:

    <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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nisarg Shah    6 年前

    在确认对话框出现时,用户界面似乎还没有更新。您可以使用 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

    注意

        2
  •  1
  •   t.niese    6 年前

    当时 confirm 调用并显示模态 this.deleting true . 但是,如果您希望vue组件执行一些不同的渲染,则会导致更改 这个。删除

    我建议将本机对话框包装为 确认 , alert , prompt 变成自己的功能。这不仅允许它们异步打开/跳转,而且还提供了以后用自定义对话框替换它们的可能性。

    await async 并承诺有一个很好的方法:

    您的对话框模块

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

    <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实现的自定义对话框的好处是,您可以在打开对话框时在后台更新信息。