Vue课程46-事件绑定-$event

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 希望 Vue 能够控制下面的这个 div,帮我们在把数据填充到 div 内部 -->
<div id="app">
<p>count 的值是:{{ count }}</p>
<!-- 如果 count 是偶数,则 按钮背景变成红色,否则,取消背景颜色 -->
<!-- <button @click="add">+N</button> -->
<!-- vue 提供了内置变量,名字叫做 $event,它就是原生 DOM 的事件对象 e -->
<button @click="add($event, 1)">+N</button>
</div>
<!-- 1. 导入 Vue 的库文件,在 window 全局就有了 Vue 这个构造函数 -->
<script src="./lib/vue-2.6.12.js"></script>
<!-- 2. 创建 Vue 的实例对象 -->
<script>
// 创建 Vue 的实例对象
const vm = new Vue({
// el 属性是固定的写法,表示当前 vm 实例要控制页面上的哪个区域,接收的值是一个选择器
el: '#app',
// data 对象就是要渲染到页面上的数据
data: {
count: 0
},
methods: {
add(e, n) {
this.count += n
console.log(e)
// 判断 this.count 的值是否为偶数
if (this.count % 2 === 0) {
// 偶数
e.target.style.backgroundColor = 'red'
} else {
// 奇数
e.target.style.backgroundColor = ''
}
}
},
})
</script>
</body>
</html>

默认会有一个事件处理的一个函数e 需要传入两个形参

posted @   前端导师歌谣  阅读(109)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示