当然,下面是每个Vue事件修饰符的代码示例。这些示例将展示如何在Vue组件中使用不同的事件修饰符。
1. .stop
- 阻止事件冒泡
<template><div @click="handleOuterClick"><button @click.stop="handleInnerClick">点击我 (阻止冒泡)</button></div>
</template><script>
export default {methods: {handleOuterClick() {console.log('外层 div 被点击了');},handleInnerClick() {console.log('按钮被点击了,但不会触发外层 div 的点击事件');}}
}
</script>
2. .prevent
- 阻止默认行为
<template><form @submit.prevent="handleSubmit"><input type="text" v-model="message" /><button type="submit">提交</button></form>
</template><script>
export default {data() {return {message: ''};},methods: {handleSubmit() {console.log('表单已提交', this.message);}}
}
</script>
3. .capture
- 使用捕获模式
<template><div @click.capture="handleCapture"><button @click="handleBubble">点击我 (捕获模式)</button></div>
</template><script>
export default {methods: {handleCapture() {console.log('事件在捕获阶段处理');},handleBubble() {console.log('事件在冒泡阶段处理');}}
}
</script>
4. .self
- 仅当事件是从该元素本身触发时才触发处理器
<template><div @click.self="handleSelfClick"><button @click="handleButtonClick">点击我 (只响应自身点击)</button></div>
</template><script>
export default {methods: {handleSelfClick(event) {if (event.target === this.$el) {console.log('只有直接点击 div 才会触发');}},handleButtonClick() {console.log('按钮被点击了');}}
}
</script>
5. .once
- 只触发一次
<template><button @click.once="handleOnceClick">只会触发一次</button>
</template><script>
export default {methods: {handleOnceClick() {console.log('这个按钮只会触发一次');}}
}
</script>
6. .passive
- 提高滚动性能(仅适用于部分浏览器)
<template><div @wheel.passive="handleScroll">滚动这里</div>
</template><script>
export default {methods: {handleScroll() {console.log('滚动了');}}
}
</script>
7. 键盘修饰符 - .enter
, .tab
, .delete
<template><input @keyup.enter="onEnterKey" placeholder="按 Enter 键提交" />
</template><script>
export default {methods: {onEnterKey() {console.log('Enter 键被按下');}}
}
</script>
8. 系统修饰键 - .ctrl
, .alt
, .shift
, .meta
<template><input @keyup.ctrl.67="onCtrlC" placeholder="按 Ctrl + C 复制" />
</template><script>
export default {methods: {onCtrlC() {console.log('Ctrl + C 被按下');}}
}
</script>
9. 鼠标按钮修饰符 - .left
, .right
, .middle
<template><button @click.left="onClickLeft">左键点击</button><button @click.right="onClickRight">右键点击</button><button @click.middle="onClickMiddle">中键点击</button>
</template><script>
export default {methods: {onClickLeft() {console.log('左键被点击');},onClickRight() {console.log('右键被点击');},onClickMiddle() {console.log('中键被点击');}}
}
</script>
10. .exact
- 控制由精确的系统修饰符组合触发的事件
<template><button @click.ctrl.exact="onCtrlClick">只有Ctrl被按下的时候触发</button>
</template><script>
export default {methods: {onCtrlClick() {console.log('只有Ctrl键被按下时触发');}}
}
</script>
以上是各个事件修饰符的代码示例。你可以根据需要选择合适的修饰符来增强你的Vue应用中的事件处理逻辑。