vue中的事件要执行的方法一般都定义在( )选项中,vue事件处理
墨初 知识笔记 103阅读
一、定义事件
Vue 元素的事件处理和 DOM 元素的很相似但是有一点语法上的不同
使用修饰符v-on:的缩写事件名的方式 给dom添加事件后面跟方法名方法名可以直接加括号如clickadd()里面进行传参。对应的事件处理函数必须在 methods对象中定义。

<template> <div> <!-- 在button上定义点击事件 --> <button clickhello(传入的参数)>你好</button> </div></template><script>export default { /** * methods 在vue定义 方法的属性对象 * 所有的方法都必须在methods里面定义 */ methods: { hello (msg) { console.log(事件触发啦哈哈哈) console.log(msg) } }}</script>
二、事件修饰符 为了更好地处理事件Vue3提供了一些便利的事件修饰符。事件修饰符可以用于改变默认事件行为、限制事件触发条件等如.stop、.prevent、.capture、.self、.once等等。下面是一些常用的事件修饰符用法
1、.stop阻止事件冒泡即停止事件在父元素中的传播。

<template> <div classbox clickhandle2> <div classbox2 clickhandle></div> </div></template><script>export default { methods: { handle () { console.log(触发) }, handle2 () { console.log(冒泡) } }}</script>
2、.prevent 阻止事件的默认行为如提交表单或点击链接后的页面跳转。
<template> <!-- 只触发点击事件不触发跳转 --> <a href click.preventhandle>百度</a></template><script>export default { methods: { handle() { console.log(触发); } },};</script>
3、.once 只触发一次事件处理方法之后解绑事件
<template> <button click.oncehandle>点击一次就失效</button></template><script>export default { methods: { handle() { console.log(触发); }, },};</script>
三、event对象 1、默认传入获取event <template> <!-- 如果事件什么都不传、并且不写() 那么事件处理函数会默认接收到event对象 --> <button clickhandle>点击</button></template><script>export default { methods: { handle(event) { console.log(event); }, },};</script>
2、携带其他参数获取event <template> <!-- 使用在template里面使用$event获取当前事件的event对象 --> <button clickhandle(第一个参数, $event)>点击</button></template><script>export default { methods: { handle(msg, event) { console.log(event); }, },};</script>
四、在函数内使用this获取当前Vue上下文 可以直接使用this.xx 使用data里定义的状态或者使用this.xx()调用methods里面定义的其他函数
注意this指向问题
<template> <button clickhandle>点击</button></template><script>export default { data() { return { num: 1, }; }, methods: { handle() { console.log(this.num); this.handle2() }, handle2() { console.log(第二个方法); }, },};</script>
标签: