一 vue 事件操作
1》监听事件
可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码。
v-on:事件名称
简写 : @事件名称
2》方法事件处理器
@事件名称=“方法名称(参数1,参数2,。。)”
3》事件修饰符
阻止冒泡
@click.stop
取消默认行为
@click.prevent
串联
@click.stop.prevent
@keyup.stop.prevent.37
4》按键修饰符
@keyup.37 ||@keyup.enter
例子1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
{{msg}}
<button @click="msg++">按钮</button>
</div>
<script src="../vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
msg: 0
},
})
</script>
</body>
</html>
例子2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
{{msg}}
<button @click="run(5)">按钮</button>
</div>
<script src="../vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
msg: 0
},
methods: {
run: function(num) {
this.msg = this.msg + num;
}
}
})
</script>
</body>
</html>
例子3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- <input type="text" @keyup="run"> -->
<input type="text" @keyup.37="run">
</div>
<script src="../vue.js"></script>
<script>
Vue.config.keyCode.f1 = 112 //给f1单独设置键值
new Vue({
el: "#app",
data: {
msg: 0
},
methods: {
run: function(e) {
var e = window.e || e;
// if (e.keyCode == 37) {
// console.log(e.keyCode)
// }
console.log(e.keyCode)
}
}
})
</script>
</body>
</html>
例子4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 取消默认行为 -->
<a :href="h" @click.prevent="run">111</a>
</div>
<script src="../vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
h: "b.html"
},
methods: {
run: function() {
alert(11)
}
}
})
</script>
</body>
</html>
例子5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#dv1 {
width: 300px;
height: 300px;
background: red;
}
#dv2 {
width: 100px;
height: 100px;
background: blue;
}
</style>
<body>
<div id="app">
<!-- 阻止冒泡 -->
<div id="dv1" @click="parent">
<div id="dv2" @click.stop="child"></div>
</div>
</div>
<script src="../vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
h: "b.html"
},
methods: {
parent: function() {
alert("父元素")
},
child: function() {
alert("子元素")
}
}
})
</script>
</body>
</html>