引入
问题:在页面中有一个按钮,当点击按钮的时候,控制台会输出“hello word”
javascript实现流程
- 获取按钮对象
- 给按钮实例绑定点击事件
代码展示
html代码
<button id="btn" type="button">按我</button>
script代码
var obtn=document.getElementById("btn2"); -- obtn.onclick=function(){ console.log("hello"); }
1.vue处理事件流程
使用v-on
指令监听Dom事件
代码展示
html代码
<button type="button" v-on:click="handleClick">click me</button>
代码解析:
v-on
可以帮助我们监听Dom事件,:
跟上对应的Dom事件类型(如click点击,mouseenter鼠标移入等),=
号后面跟上函数或者直接一些javascript代码。在实际开发中,如果把js代码写在等号后面是不太实际的,我们可以使用一个函数变量将这些代码存储起来,而在等号后面,我们则可以写上方法名字。如v-on:click=“handleClick”
2.在methods方法属性中注册相应函数
methods:{
handleClick:function(){
console.log('hello');
}
}`
效果图:
2.事件对象
有事件产生的地方就会涉及到事件对象,接下来小结如何获取到事件对象。
2.1方法名后不加括号
<code> v-on:click="handleClick"</code>
methods:{
handleClick:function(e){
console.log(e);
}
}
代码解析:
如果方法名后不加括号,我们可以在methods 方法属性中的对应的方法函数中加入一个参数即可。
控制台输出
MouseEvent {isTrusted: true, screenX: 162, screenY: 153, clientX: 47, clientY: 22, …}
2.2 方法名后加括号
<button type="button" v-on:click="handleClick()">click me</button>
methods:{
handleClick:function(e){
console.log(e);
}
}
控制台输出:
undefined
方法名后不加指定参数,在方法中是无法获取到事件对象。
解决方法:在方法名括号中输入参数$event;
<button type="button" v-on:click="handleClick($event)">click me</button>
methods:{
handleClick:function(e){
console.log(e);
}
}
控制台输出:
MouseEvent {isTrusted: true, screenX: 100, screenY: 116, clientX: 57, clientY: 26, …}
2.2 方法名后加括号,括号内多个参数
<button type="button" v-on:click="handleClick('a','b',$event)">click me</button>
methods:{
handleClick:function(d,f,g){
console.log(d);
console.log(f);
console.log(g);
}
}
控制台输出:
a
b
MouseEvent {isTrusted: true, screenX: 100, screenY: 116, clientX: 57, clientY: 26, …}