v-on基本使用和语法糖
在前端开发中,我们需要经常和用户交互。
1.这个时候,我们就必须监听用户发生的事件,比如点击、拖拽、键盘事件等等。
2.在Vue中如何监听事件呢?使用v-on指令
v-on介绍:
作用:绑定事件监听器
缩写:@
预期:function | inline statement | Object
参数:event
语法糖:
<button @click="increment">+</button>
<button @click="decrement">-</button>
栗子:
<!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">
<h4>当前计数为:{{counter}}</h4>
<!-- <button v-on:click="counter++">+</button>
<button v-on:click="counter--">-</button> -->
<!-- <button v-on:click="increment">+</button>
<button v-on:click="decrement">-</button> -->
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
<script src="../2020-6-Vuejs/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
counter: 0,
},
methods: {
increment() {
this.counter++;
},
decrement() {
this.counter--;
}
}
})
</script>
</body>
</html>