在 Vue 中使用 $refs 触发 'click' 之前有条件地更新 INPUT 元素的属性
Conditionally update attributes of INPUT element before 'click' is triggered with $refs in Vue
我正在有条件地更新输入元素的属性,然后使用 $refs 触发输入的点击...从模态一次完成。
问题是点击在属性改变之前触发,所以我添加了一个 10 毫秒的 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
函数的回调传递给它。
您可以从官方docs
了解更多关于nextTick
的信息
我正在有条件地更新输入元素的属性,然后使用 $refs 触发输入的点击...从模态一次完成。
问题是点击在属性改变之前触发,所以我添加了一个 10 毫秒的 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
函数的回调传递给它。
您可以从官方docs
了解更多关于nextTick
的信息