1、事件绑定
1.1、事件绑定
-
实现:
// 模板里面 <标签 v-on:事件类型="事件函数"></标签> // 缩写 <标签 @事件类型="事件函数"></标签>
// JS里面 new Vue({ .... methods:{ // 事件 事件函数:function(){ ... } } })
1.2、事件传参
-
实现:
// 缩写 <标签 @事件类型="事件函数(实参)"></标签>
// JS里面 new Vue({ .... methods:{ // 事件 事件函数:function(形参){ // 形参就是上面调用时候传递的数据 ... } } })
1.3、事件对象
-
实现:
// 缩写 <标签 @事件类型="事件函数"></标签>
// JS里面 new Vue({ .... methods:{ // 事件 事件函数:function(形参){ // 形参就是事件对象! 形参一般用 e ev event 标识符表示 ... } } })
1.4、既要传参又要获取事件对象
-
实现
// 缩写 <标签 @事件类型="事件函数(实参,$event)"></标签>
// JS里面 new Vue({ .... methods:{ // 事件 事件函数:function(形参,ev){ // 和上面实际传入一一对应。 $event就表示事件对象。 ... } } })
1.5、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06、事件相关</title>
<script src="./vue.js"></script>
<style>
.box{
border:2px solid blue;
width: 100px;
height: 100px;
text-align: center;
color: #fff;
}
</style>
</head>
<body>
<div id="app">
{{num}}
<!-- <button v-on:click="say">点击一下!</button> -->
<button @click="say">点击一下!</button>
<div class="box" @click="change"></div>
<hr>
<button @click="setNum(10)">将num设为10</button>
<button @click="setNum(20)">将num设为20</button>
<button @click="setNum(40)">将num设为40</button>
<div class="box" @click="setinfo('你好',$event,'red')"></div>
<div class="box" @click="setinfo('天下第一!',$event,'blue')"></div>
</div>
</body>
<script>
new Vue({
el:"#app", // 作用的范围
data:{ // 数据
num:1
},
methods:{ // 事件
say:function(){
console.log(this.num)
this.num++;
},
change:function(ev){ // 【形参表示事件对象】
// console.log(ev.target) // 就是当前这个节点对象 div#box
// Math.random() 生成一个0-1 之间的随机小数,包含0 不包含1
// Math.floor() 向下取整
let r = Math.floor(Math.random() * 256) // [0,255]
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
ev.target.style.backgroundColor= "rgb("+r+","+g+","+b+")"
console.log("change")
},
setNum:function(x){ // 【形参就是上面调用时候传递的数据!】
console.log(x)
this.num = x;
},
setinfo:function(str,event,color){
console.log(str)
console.log(event)
console.log(color)
event.target.style.backgroundColor = color;
event.target.innerHTML = str;
}
}
})
</script>
</html>