1. Add an event listener v-on
(1) using v-on instruction can add event listeners, syntax:
v-on: eventName = "the Fn" can be abbreviated to @: eventName = "the Fn"
(2) parameters: $ event is the element event of the current trigger, even if does not pass $ event, you can also use the event this parameter in the callback function
Basic use:
<div id="app">
<button v-on:click="test">点我</button>
<button v-on:click="test2('hello vue')">点我2</button>
<button v-on:click="test3($event)">点我3</button>
<button v-on:click="test4">点我4</button>
</div>
methods: {
test() {
console.log('hi');
},
test2(content) {
console.log(content);
},
test3(event) {
console.log(event.target);
},
test4(){
//即使不传$event,在回调函数中也可以使用event这个参数
console.log(event.target.innerText);
}
}
Other events:
<body>
<div id="app">
<!-- 点击事件 -->
<button @click="testClick">点我</button>
<!-- input事件 -->
<input type="text" @input="testInput">
<!-- change事件 -->
<select @change="testChange">
<option value="020">广州</option>
<option value="021">上海</option>
</select>
</div>
</body>
<script>
new Vue({
el:"#app",
data:{},
methods:{
testClick(){
console.log('Click')
},
testInput(){
console.log('Input')
},
testChange(){
console.log('Change')
}
}
})
</script>
2. Event Modifier
Event modifier used to control the bubbling of events and default behavior, there are two:
.stop: to prevent the event from bubbling
.prevent: to prevent the default event
Basic use:
<!-- 阻止事件冒泡 -->
<div id="big" @click="test">
<div id="small" @click.stop="test2"></div>
</div>
<!-- 阻止默认事件,点击a链接不会发生跳转,只会执行test方法的代码 -->
<a href="https://www.baidu.com/" @click.prevent="test">百度一下</a>
3. modifier keys
Key modifiers used to monitor whether a key is pressed
Use @keyup keyboard commands you can add events to the elements, such as:
<!-- 任何按键按下都会触发回调函数 -->
<textarea @keyup="testKeyup" cols="30" rows="10"></textarea>
If we want to press a specific key callback is triggered only if you add a modifier key or key code, for example:
Syntax: @keyup key modifier = callback function.
Syntax: @keyup key code = callback function.
<!-- 只有回车键按下的时候才会触发回调函数 -->
<!-- 下面的两种写法效果是一致的 -->
<!--使用按键码,回车键的keyCode是13 -->
<textarea @keyup.13="testKeyup" cols="30" rows="10"></textarea>
<!--使用按键修饰符,因为回车键比较常用,所以vue为他设置了名称,可以直接使用enter来代替。 -->
<textarea @keyup.enter="testKeyup" cols="30" rows="10"></textarea>
methods: {
testKeyup() {
console.log('回车键被按下了');
}
}
Vue provides the vast majority of commonly used modifier keys:
- .enter
- .tab
- .delete (capture "Delete" and "backspace" key)
- .esc
- .space
- .up
- .down
- .left
- .right
Remaining keys with key code
<!--q的keyCode是81,当按下q键时会触发test方法 -->
<input type="text" value="hello" @keyup.81="test">
You can custom key Vue.config.keyCodes = modified by the global key code from the key definition of modifiers, for example:
//q的keyCode是81
<input type="text" value="hello" @keyup.q="test">
Vue.config.keyCodes.q=81