在Vue中,若想添加點擊事件,需要使用v-on:click進行點擊事件的添加。對於v-on:click,可以簡寫爲@click。而點擊事件的內容可以爲具體的代碼或者是函數。
在Vue中,定義函數需要new Vue()中,格式爲:
methods: {
函數名: function() {
函數體
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue計數器</title>
</head>
<body>
<div id="app">
<h1>當前計數: {{counter}}</h1>
<!-- v-on:click代表js中的點擊函數,點擊之後會觸發點擊事件-->
<!-- v-on:click的內容可以有兩種形式:具體的代碼、函數-->
<!-- <button v-on:click="counter++">+</button>-->
<!-- <button v-on:click="counter--">-</button>-->
<!-- v-on:click可以簡寫爲@click-->
<button @click="add">+</button>
<button @click="sub">-</button>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
add: function () {
this.counter++;
console.log("計數器加1");
},
sub: function () {
this.counter--;
console.log("計數器減1");
}
}
})
</script>
</body>
</html>