首页 > 解决方案 > 在 Vue 中使用 $refs 触发“click”之前有条件地更新 INPUT 元素的属性

问题描述

我正在有条件地更新输入元素的属性,然后使用 $refs 触发输入的点击...从模式中一次性完成。

问题是在属性改变之前点击被触发,所以我添加了一个 10ms 的 setTimeout,它已经解决了这个问题。

当然,有更好、更 Vue 的方式来做到这一点吗?

输入元素:

      <input
        ref="file"
        type="file"
        name=""
        :multiple="!androidCameraToggle"
        :capture="androidCameraToggle"
        :accept="[androidCameraToggle ? 'image/*' : 'image/*;capture=camera']"
        style="display:none"
        @change="addImage"
      >

数据:

data () {
    return {
      androidCameraToggle: false
    }
  },

模态:

    async sourcePrompt() {
      const swalWithBootstrapButtons = this.$swal.mixin({
        customClass: {
          confirmButton: 'btn btn-primary p-2',
          cancelButton: 'btn btn-primary p-2'
        }
      })
      swalWithBootstrapButtons.fire({
        title: 'Upload Photo',
        text: "Choose image source.",
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Camera',
        cancelButtonText: 'Photo Album'
      }).then((result) => {
        if (result.value) {
          this.androidCameraToggle = true
          let fileInput = this.$refs.file
          setTimeout(function(){ fileInput.click()}, 10)
        } else if (result.dismiss === swalWithBootstrapButtons.DismissReason.cancel) {
          this.androidCameraToggle = false
          let fileInput = this.$refs.file
          setTimeout(function(){ fileInput.click() }, 10)
        }
      })
    }

标签: javascripthtmlvue.jscapacitor

解决方案


你可以使用this.$nextTick()api。

nextTick(callback)- 回调函数将在下一次 html 更新后执行。因此,当您更新 html 元素的属性时。nextTick将在 html 完成更新后调用。它有点像mounted钩子,但在每次 html 更新后触发。nextTick因此,要触发您的单击事件侦听器,您必须在更新属性值后传递它具有函数的回调。

nextTick您可以从官方文档中了解更多信息


推荐阅读