我有一个带有各种选项的选择字段。当用户单击该字段以更改当前选择时,我需要启动一个提示让用户确认他们希望继续进行更改,因为这将需要他们重做一个漫长的过程。如果他们取消更改,则需要防止所选选项发生更改,因为即使是快速的临时更改也会触发客户端上的自动保存。因此,似乎 other solutions不要工作,因为他们保存原始值,让更改通过,然后在必要时恢复更改。
我不确定这是否是“正确”的方法,但我决定创建一个每次单击选择字段时都会运行的函数。我通过使用原生 confirm
成功解决了这个问题下面代码中的方法。我相信它有效,因为 confirm
的同步特性允许我在任何事件监听器收到更改之前还原更改,因此基本上就像更改从未发生过一样(如果我错了,请纠正我)。不幸的是,我不允许使用 confirm
由于兼容性原因。
// This works, but I need to be able to do it without using 'confirm'
handlePotentialOptionChange(e){
if (this.currentOption !== e.target.value){
if (!confirm(`Are you sure you want to change the option from ${this.currentOption} to ${e.target.value}? You will be required to redo multiple fields.`)){
this.selectModel = this.currentOption // If user cancels the change, revert it to the original option.
}
}
}
因为我不能使用
confirm
,我使用的是 dialog component from Buefy .但是,它是异步运行的,这意味着当用户尝试选择不同的选项时,选项更改将在他们回答对话框之前完成。如果取消,下面的代码将恢复更改,但到那时已经太晚了,无法使用。handlePotentialOptionChange(e){
if (this.currentOption !== e.target.value){
this.$dialog.confirm({
message: `Are you sure you want to change the option from ${this.currentOption} to ${e.target.value}? You will be required to redo multiple fields.`,
onConfirm: () => this.selectModel = e.target.value,
onCancel: () => this.selectModel = this.currentOption
})
}
}
是否可以让用户看到选项下拉列表,但在提示得到回答之前禁用任何类型的选项更改,以便我可以在异步
onConfirm
中相应地更改选项和 onCancel
功能?还是我应该使用某种完全不同的方法?谢谢你。
最佳答案
我将创建一个组合选择元素和确认对话框的新组件,并让它发出一个“输入”事件(仅当新选择已被确认时)并接收一个“值” Prop ,以便父级可以将它与 v- 一起使用模型。
运行代码片段并阅读下面的示例。
Vue.component('select-confirm', {
props: ['value'],
data: function () {
return {
showConfirmationDialog: false,
unconfirmedValue: 'a'
}
},
methods: {
cancelSelection () {
this.showConfirmationDialog = false
},
confirmSelection () {
this.$emit('input', this.unconfirmedValue)
this.showConfirmationDialog = false
},
showConfirmation (e) {
this.unconfirmedValue = e.currentTarget.value
this.showConfirmationDialog = true
}
},
template: `
<div class="select-confirm">
<select :value="value" @change="showConfirmation">
<option value="a">A</option>
<option value="b">B</option>
</select>
<div v-if="showConfirmationDialog" class="confirmation-dialog">
<p>Are you sure you want to change your selection to '{{ this.unconfirmedValue }}'?</p>
<button @click="confirmSelection">Yes</button>
<button @click="cancelSelection">No</button>
</div>
</div>
`
})
new Vue({
el: '#app',
data () {
return {
confirmedValue: 'a'
}
}
})
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<div id="app">
<select-confirm v-model="confirmedValue"></select-confirm>
<p>Confirmed value is '{{ confirmedValue }}'.</p>
</div>
关于javascript - 如何防止选择表单被更改,直到 Vue 中的对话框完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696976/