<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<button v-on:click="increase">Click me</button>
<p>{{counter}}</p>
</div>
example 1
new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
increase: function() {
this.counter++
}
}
});
这里我们给button增加了一个v-on directive,后面跟的参数click代表一个事件,可以是任何和按钮有关的事件,等号右侧的值是事件发生后要调用的函数。
example 2
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<button v-on:click="increase">Click me</button>
<p>{{counter}}</p>
<p v-on:mousemove="updateCoordinate">Coordinates: {{X}}/{{Y}}</p>
</div>
new Vue({
el: '#app',
data: {
counter: 0,
X: 0,
Y: 0
},
methods: {
increase: function() {
this.counter++
},
updateCoordinate: function() {
this.X = event.clientX;
this.Y = event.clientY;
}
}
});
这里我们可以发现,mousemove这个event还自动的在调用的函数里加入event参数,里面包含光标的坐标信息。
example 3
那如果想给这些事件的响应函数里传入自定义的参数呢?
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<button v-on:click="increase(2, $event)">Click me</button>
<p>{{counter}}</p>
<p v-on:mousemove="updateCoordinate">Coordinates: {{X}}/{{Y}}</p>
</div>
new Vue({
el: '#app',
data: {
counter: 0,
X: 0,
Y: 0
},
methods: {
increase: function(step, event) {
this.counter = this.counter+2
},
updateCoordinate: function(event) {
this.X = event.clientX;
this.Y = event.clientY;
}
}
});