Vue.js官方文档对于 v-on 这一常用指令提供了缩写方法,看看官网是怎么介绍的


<!--完整语法--><av-on:click="doSomething"></a><!--缩写--><a@click="doSomething"></a>


1、方法事件处理器

可以用 v-on 指令监听DOM事件

<divid="box"><buttonclass="btnbtn-success"v-on:click="showMsg">`msg`</button></div>


绑定一个单机事件的处理方法showMsg到methods中

varvm=newVue({el:'#box',//el指代选择器如id,class,tagNamedata:{msg:'点击按钮',name:'Vue.js'},methods:{//在methods对象中定义方法showMsg:function(e){//方法中的this,指代newVue这个实例对象,可以再次验证下console.log(this);//event是原生DOM事件console.log(e.target);//打印出事件源对象buttonconsole.log('Hello'+this.name+'!');}}});


查看页面效果截图


2、内联语句处理器

除了直接绑定到一个方法里面,也可以用内联Javascript语句

<divclass="app"><buttonclass="btnbtn-default"v-on:click="say('hi')">SayHi</button><!--尝试用下v-on的缩写方法@click--><buttonclass="btnbtn-primary"@click="say('what')">SayWhat</button></div>

varvm2=newVue({el:'.app',methods:{say:function(msg){//把方法里面的参数打印出来console.log(msg);}}});


查看页面效果截图

有时也需要在内联语句处理器中访问原生DOM事件,比如阻止链接跳转。可以用特殊变量$event把它传入方法:

<divclass="app"><ahref="http://cn.vuejs.org/guide/events.html"@click="stop(test,$event)">打开Vue官网</a></div>

varvm2=newVue({el:'.app',data:{test:'阻止链接跳转'},methods:{stop:function(test,e){e.preventDefault();alert(test);}}});


点击a链接以后,页面还能跳转到vue官网吗?看看页面效果截图


3、事件修饰符

在事件处理器中经常需要调用event.preventDefault()或event.stopPropagation()。尽管在方法内可以轻松做到(如上例所示),不过让方法是纯粹的数据逻辑而不处理DOM事件细节会更好。


为了解决这个问题,Vue为v-on提供了两个事件修饰符:.prevent和.stop

<!--阻止单击事件冒泡--><av-on:click.stop="doThis"></a><!--提交事件不再重载页面--><formv-on:submit.prevent="onSubmit"></form><!--修饰符可以串联--><av-on:click.stop.prevent="doThat"><!--只有修饰符--><formv-on:submit.prevent></form><!--添加事件侦听器时使用capture模式--><divv-on:click.capture="doThis">...</div><!--只当事件在该元素本身(而不是子元素)触发时触发回调--><divv-on:click.self="doThat">...</div>

看一小段代码理解下上面的大段内容:

<divid="container"><!--阻止页面跳转--><av-on:click.prevent="doThis"href="http://cn.vuejs.org/guide/events.html">doThis</a></div>

varvm3=newVue({el:'#container',methods:{doThis:function(){}}});

最终的实际结果就是,点击a链接,并不会跳转到Vue官网,完全实现了我们预期的效果。


再来看一个关于.self的例子

<divid="app"><div@click.self="test"class="a">a<divclass="b">b</div></div></div>

varvm4=newVue({el:'#app',data:{items:'test'},methods:{test:function(e){console.log(e);}}})


根据Vue的文档解释“只当事件在该元素本身(而不是子元素)触发时触发回调”,所以点class为a的div时触发了事件,点class为b的div时则不会


4、按键修饰符

http://dapengtalk.blog.51cto.com/11549574/1860203

在这边博文中,我专门复习了keycode的相关知识。在Vue中也专门为键盘监听事件提供了一系列的按键修饰符

<!--只有在keyCode是13时调用vm.submit()--><inputv-on:keyup.13="submit"><!--同上--><inputv-on:keyup.enter="submit">


全部的按键别名:

enter

tab

delete

esc

space

up

down

left

right


5、为什么在HTML中监听事件?

(1)、扫一眼HTML模板便能轻松定位在Javascript代码里对应的方法。

(2)、因为你无需在Javascript里手动绑定事件,你的ViewModel代码可以是非常纯粹的逻辑,和DOM完全解耦,更易于测试。

(3)、当一个ViewModel被销毁时,所有的事件处理器都会被自动删除,你无需担心如何自己清楚它们


学习的过程中参考了以下文档,诚挚感谢

http://cn.vuejs.org/guide/events.html

http://blog.csdn.net/qq20004604/article/details/52413898