<p>{{age}}</p>
<button type="button" v-on:click="increment">Increment</button>
<button type="button" v-on:click="age--">Decrement</button>
increment() {
this.age++
}
通过将 v-on:
添加在其他JS事件属性前(如click,input)可以实现在事件发生时调用 app 的方法。这里不加()是因为不需要传递参数。
通常我们使用简写方式,用@
代替:
<button type="button" @click="increment">Increment</button>
<button type="button" @click="age--">Decrement</button>
带参
带参数方法需要在最后传入事件变量:
<input
type="text"
:value="firstName"
@input="updateFirstName('hello word', $event)"
/>
同时得处理掉默认事件动作,就像网页htmlcss开始先将所有边距和填充设为0一样。
updateFirstName(str, event) {
event.preventDefault()
console.log(str)
this.firstName = event.target.value
}
相关
v-model 数据绑定 实际上就是由 v-bind 属性值绑定 和 v-on 事件监听 组合起来的语法糖,一下两种写法是等价的:
<input type="text" :value="firstName" @input="updateFirstName" />
<input type="text" v-model="firstName" />