扩展Vue.js v-on:click指令 [英] Extend Vue.js v-on:click directive
问题描述
我是 vuejs 的问题.我正在尝试创建我的第一个应用程序.我想在每次单击按钮时显示一条确认消息.
I'm new to vuejs. I'm trying to create my first app. I would like to show a confirm message on every click on buttons.
示例:
<button class="btn btn-danger" v-on:click="reject(proposal)">reject</button>
我的问题是:我可以扩展v-on:click
事件以在各处显示确认吗?我将创建名为v-confirm-click
的自定义指令,该指令首先执行确认,然后如果我单击确定",则执行click事件.有可能吗?
My question is: Can I extend the v-on:click
event to show the confirm everywhere? I would make my custom directive called v-confirm-click
that first executes a confirm and then, if I click on "ok", executes the click event. Is it possible?
推荐答案
我建议改用一个组件. Vue中的指令通常用于直接DOM操作.在大多数情况下,如果您认为需要使用指令,则使用组件会更好.
I would recommend a component instead. Directives in Vue are generally used for direct DOM manipulation. In most cases where you think you need a directive, a component is better.
这是确认按钮组件的示例.
Here is an example of a confirm button component.
Vue.component("confirm-button",{
props:["onConfirm", "confirmText"],
template:`<button @click="onClick"><slot></slot></button>`,
methods:{
onClick(){
if (confirm(this.confirmText))
this.onConfirm()
}
}
})
您可以这样使用:
<confirm-button :on-confirm="confirm" confirm-text="Are you sure?">
Confirm
</confirm-button>
这里是一个例子.
console.clear()
Vue.component("confirm-button", {
props: ["onConfirm", "confirmText"],
template: `<button @click="onClick"><slot></slot></button>`,
methods: {
onClick() {
if (confirm(this.confirmText))
this.onConfirm()
}
}
})
new Vue({
el: "#app",
methods: {
confirm() {
alert("Confirmed!")
}
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<confirm-button :on-confirm="confirm" confirm-text="Are you sure?">
Confirm
</confirm-button>
</div>
这篇关于扩展Vue.js v-on:click指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!