有很多类似delete
之类的操作必须由用户再次确认才能执行,我很累每次都要重复确认工作,所以我尝试通过vue指令来实现。
类似的东西:
Vue.directive("confirm", {
bind(el, binding, vnode) {
el._listener = function (e) {
if(confirm(binding.value)){
//do nothing,
}else{
e.stopImmediatePropagation(); // stop other events in this element
}
}
el.addEventListener("click", el._listener)
},
unbind(el, binding, vnode) {
el._listener && el.removeEventListener("click", el._listener) && (el._listener = null)
}
});
//组件
<button v-confirm @click="delete()">Delete</button>
但是,它不起作用。我发现调用confirm()
时,组件中@click
绑定的事件侦听器已经被调用。
有什么办法解决这个问题?
答案 0 :(得分:0)
执行自定义指令中的bind
挂钩函数时,在组件上获取click函数
Vue.directive("confirm", {
bind(el, binding, vnode) {
let handleFunction = binding.value
el._listener = function(e) {
if (confirm("Are you sure.....")) {
//do nothing,
alert("I'm sure")
handleFunction && handleFunction()
} else {
e.stopImmediatePropagation(); // stop other events in this element
alert("Cancel")
}
}
el.addEventListener("click", el._listener)
},
unbind(el, binding, vnode) {
el._listener && el.removeEventListener("click", el._listener) && (el._listener = null)
}
});
new Vue({
el: "#app",
methods: {
deleteHandle() {
console.log('delete')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-confirm:click="deleteHandle">Delete</button>
</div>