javascript - 在 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)
}
})
}
解决方案
你可以使用this.$nextTick()
api。
nextTick(callback)
- 回调函数将在下一次 html 更新后执行。因此,当您更新 html 元素的属性时。nextTick
将在 html 完成更新后调用。它有点像mounted
钩子,但在每次 html 更新后触发。nextTick
因此,要触发您的单击事件侦听器,您必须在更新属性值后传递它具有函数的回调。
nextTick
您可以从官方文档中了解更多信息
推荐阅读
- excel - Scala不读取Excel文件
- php - 如何使用php将第二个数组值插入第一个数组
- python - 使用没有 with 语句 Python 的 ThreadPoolExecutor
- java - 使用 Okhttp formdata 登录网站
- java - 如何解决这个 java 问题硬件中的低估案例(USACO Silver)
- batch-file - 对于 /F findstr 设置 CSV 的第二列的值
- r - 使用汇总 r 进行逻辑值计数
- c++ - 如何使用箭头在 QtVirtualKeyboard 中导航
- vb.net - 在 VB.NET 中根据宽度和高度生成空白图像
- omnet++ - omnetpp 始终以退出代码结束 1