v-on绑定事件监听,简写为@(语法糖)
v-on绑定点击时间实现数据增减的小例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h2 {
display: inline;
margin: 20px;
}
</style>
</head>
<body>
<div id="app">
<!-- button绑定点击事件 increasement 不需要传参可以不加() -->
<button @click = 'incresement'>+</button>
<h2>{{counter}}</h2>
<button @click = 'decresement'>-</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
counter : 0 //定义计数器
},
methods : {
//定义增加和减少时调用的函数 可以省略:function
incresement:function(){
this.counter++;
},
decresement(){
this.counter--;
}
}
})
</script>
</body>
</html>
含有形参的函数绑定事件时,加()和不加()的区别
函数本身不需要参数时,可直接省略()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 按钮1 2 绑定相同事件btn1 btn2,被绑定事件包含形参
button1绑定点击事件加(),但不传实参,默认为undefined
button2不加(),默认传入原生事件 MouseEvent{isTrusted: true....}
-->
<button @click = 'btn1()'>button1</button>
<button @click = 'btn2'>button2</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
msg :'hello'
},
methods: {
btn1(arg){
console.log(arg);
},
btn2(arg){
console.log(arg);
}
}
})
</script>
</body>
</html>

同时需要普通参数和event的时候,需要通过$event传递实参
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click ='btn3(123,$event)' >button3</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
msg :'hello'
},
methods: {
btn3(arg,event){
console.log(arg,event);
}
}
})
</script>
</body>
</html>

.stop - 阻止事件冒泡
.prevent - 阻止默认行为
.native - 监听组件根元素的原生事件。
.once - 只触发一次回调