vue事件处理1

一、事件处理

  1. vue指令绑定事件,v-on:简写为@
    无参函数
    v-on:click=“方法名”
    @click=“方法名”
    有参函数
 v-on:click="方法名($event,param...)"
  @click="方法名($event,param...)"//$event表示event
  1. 创建vue实例对象,在vue实例对象的mothods属性中,编写事件方法
    new Vue({
    el:
    data:
    methods:{
    方法名(event){//此处this代表vue对象或组件
    }

})

二、事件修饰符

  1. 阻止默认事件prevent
    js写法:function 方法名(event){
    event.preventDefault();
    }
    vue写法:
    @click.prevent=“方法名”

  2. 阻止事件冒泡stop

			<div class="demo1" @click="showInfo">
				<button @click="showInfo">点我提示信息</button>
				<!-- 修饰符可以连续写 -->
				<!-- <a href="http://www.atguigu.com" @click.prevent.stop="showInfo">点我提示信息</a> -->
			</div>

js写法:function 方法名(event){
event.stopPropagation();
}
vue写法:
@click.stop=“方法名” //在写最内层的函数前加上
<button @click.stop=“showInfo”>点我提示信息
3. 事件只触发一次
vue写法:
@click.once=“方法名”
<button @click.stop=“showInfo”>点我提示信息 5.

4.caputure:捕获时处理时间

	<!-- 使用事件的捕获模式 -->
			<div class="box1" @click.capture="showMsg(1)">
				div1
				<div class="box2" @click="showMsg(2)">
					div2
				</div>
			</div>

5.self 只有event.taget为当前操作元素时才触发事件

<!-- 只有event.target是当前操作的元素时才触发事件; -->
			<div class="demo1" @click.self="showInfo">
				<button @click="showInfo">点我提示信息</button>
			</div>
new Vue({
			el:'#root',
			data:{
			},
			methods:{
				showInfo(e){
					//alert('同学你好!')
				console.log(e.target)
				},
				showMsg(msg){
					console.log(msg)
				}
				}
		})

6.passive:事件的默认行为立即执行,无需等待事件回调执行完毕;

<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
<!--@Scroll滚动条触发事件,@where滚轮滚动触发事件-->
			<ul @wheel.passive="demo" class="list">
				<li>1</li>
				<li>2</li>
				<li>3</li>
				<li>4</li>
			</ul>

new Vue({
			el:'',
			data:{
				
			},
			methods:{
								demo(){
					for (let i = 0; i < 100; i++) {
						console.log('#')
					}
					console.log('累坏了')
				}
			}
		})

@wheel.passive滑块会先下/上滑(移动),再执行demo()函数
@wheel 先执行demo()函数,滑块再下/上滑(移动),

三、键盘事件

@keydown //按下键盘按键
@keyup //按下键盘按键并松手
e.keyCode// 键盘字符编码

常用按键别名

  • enter回车 //回车键触发事件
		<div id="test">
			
			<input type="text" placeholder="按下回车提示输入" @keyup.enter="showInfo">
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
		new Vue({
			el:'#test',
			data:{
				
			},
			methods: {
				showInfo(e){
					// console.log(e.key,e.keyCode)
					console.log(e.target.value)
				}
			},
		})
	</script>
</html>
  1. delete //删除(退格)键,触发事件
    <input type=“text” placeholder=“按下回车提示输入” @keyup.delete=“showInfo”>

以下使用方法同上
3. esc //退出键触发事件
4. space //空格键触发事件
5. tab //换行键触发事件
6. up //上键触发事件
7. down //下键触发事件
8. left ///左键触发事件
9. right ///右键触发事件

e.key //按键名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值