百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程文章 > 正文

JS,Vue2,事件处理,计算属性,监视属性,class与style绑定

qiyuwang 2024-10-06 12:21 15 浏览 0 评论

VUE事件处理

用v-on指令或者@监听DOM事件,并在触发时运行一些JavaScript代码;

参考:JS,Vue2,介绍,与Vue3区别,MVVM设计模式,模板语法,数据绑定

Vue中的事件修饰符:

1、prevent:阻止默认事件(常用);

2、stop:阻止事件冒泡(常用);

3、once:事件只触发一次(常用);

4、capture:使用事件的捕获模式;

5、self:只有event.target是当前操作的元素时才触发事件;

6、passive:事件的默认行为立即执行,无需等待事件回调执行完毕;

Vue中常用的按键别名:

回车 => enter、删除 => delete (捕获“删除”和“退格”键)、退出 => esc、空格 => space、换行 => tab (特殊,必须配合keydown去使用)、上 => up、下 => down、左 => left、右 => right等。

代码案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>VUE2事件处理</title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
        <!-- 
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
        -->
		<style>
			.demo1{
				height: 50px;
				background-color: skyblue;
			}
			.box1{
				padding: 5px;
				background-color: skyblue;
			}
			.box2{
				padding: 5px;
				background-color: orange;
			}
			.list {
				width: 200px;
				height: 200px;
				background-color: peru;
				overflow: auto;
			}
			li {
				height: 100px;
			}
		</style>
	</head>
	<body>
        <div id="app">
            <h2>{{name}}++</h2>
			<button v-on:click="showInfo1">提示信息1</button> -->
			<button @click="showInfo2">提示信息2</button> -->
			<button @click="showInfo3($event,666)">提示信息3(传参)</button>
			<hr/>
			<!-- 
				Vue中的事件修饰符:
				1、prevent:阻止默认事件(常用);
				2、stop:阻止事件冒泡(常用);
				3、once:事件只触发一次(常用);
				4、capture:使用事件的捕获模式;
				5、self:只有event.target是当前操作的元素时才触发事件;
				6、passive:事件的默认行为立即执行,无需等待事件回调执行完毕;
			-->
			<!-- 阻止默认事件(常用) -->
			<a href="https://www.toutiao.com/c/user/token/MS4wLjABAAAA04-54E8cnKw5hC4US0MxdKuKxFAb5RbaGtfKx1ml_CE/" @click.prevent="showInfo1">提示信息</a>
			<br />
			<!-- 阻止事件冒泡(常用) -->
			<div class="demo1" @click="showInfo1">
				<button @click.stop="showInfo1">提示信息</button>
				<!-- 修饰符可以连续写 -->
				<!--
					<a href="https://www.toutiao.com/c/user/token/MS4wLjABAAAA04-54E8cnKw5hC4US0MxdKuKxFAb5RbaGtfKx1ml_CE/" @click.prevent.stop="showInfo1">提示信息</a> 
				-->
			</div>
			<br />
			<!-- 事件只触发一次(常用) -->
			<button @click.once="showInfo1">提示信息</button>
			<br />
			<!-- 使用事件的捕获模式 -->
			<div class="box1" @click.capture="showMsg(1)">
				div1
				<div class="box2" @click="showMsg(2)">
					div2
				</div>
			</div>
			<br />
			<!-- 只有event.target是当前操作的元素时才触发事件; -->
			<div class="demo2" @click.self="showInfo1">
				<button @click="showInfo1">提示信息</button>
			</div>
			<br />
			<!-- onwheel事件在鼠标滚轮在元素上下滚动时触发; -->
			<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
			<ul @wheel.passive="showDemo" class="list">
				<li>111111112</li>
				<li>222222222</li>
				<li>333333333</li>
				<li>444444444</li>
			</ul>
			<!-- 键盘事件 -->
			<!-- 
				1、Vue中常用的按键别名:
							回车 => enter
							删除 => delete (捕获“删除”和“退格”键)
							退出 => esc
							空格 => space
							换行 => tab (特殊,必须配合keydown去使用)
							上 => up
							下 => down
							左 => left
							右 => right
				2、Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
				3、系统修饰键(用法特殊):ctrl、alt、shift、meta
							(1)、配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发。
							(2)、配合keydown使用:正常触发事件。
				4、也可以使用keyCode去指定具体的按键(不推荐)
				5、Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名
			-->
			<input type="text" placeholder="按下回车提示输入" @keydown.enter="showInfo1">
        </div>
        <script type="text/javascript" >
			// 阻止vue在启动时生成生产提示
			Vue.config.productionTip = false;
			// 创建Vue实例
			const vm = new Vue({
				el:'#app',
				data:{
					name:'小奋斗',
				},
				methods:{
					showInfo1(event){
						console.log(event.target.innerText) // 提示信息1
						console.log(this) // vm
						alert('提示信息1')
					},
					showInfo2(event){
						console.log(event.target.innerText) // 提示信息2
						console.log(this) // vm
						alert('提示信息2')
					},
					showInfo3(event,number){
						console.log(event,number) // PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …} 666
						console.log(event.target.innerText) //  提示信息3(传参)
						console.log(this) // vm
						alert('提示信息3(传参)')
					},
					showMsg(msg){
						console.log(msg)
					},
					showDemo(){
						for (let i = 0; i < 1000; i++) {
							console.log('#');
						}
						console.log('累坏了')
					}
				}
			});
		</script>
	</body>
</html>

VUE计算属性

模板内的表达式是非常便利的,用于简单的运算。当其过长或逻辑过于复杂时,会难以维护,因此,当遇到复杂的逻辑时应该使用计算属性,用computed计算属性。

代码案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>VUE2计算属性</title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
        <!-- 
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
        -->
	</head>
	<body>
        <div class="app">
			<h1>{{name}}</h1>
			<hr>
			<ul>
				<li>
					通过methods来完成
				</li>
			</ul>
			<input type="text" v-model="firstName" />
			<input type="text" v-model="lastName" />
			全名:{{fullName()}}
			<hr>
			<ol>
				<li>通过改变firstName2和lastName2来改变fullName2</li>
				<li>通过改变fullName2来调整firstName2和lastName2</li>
			</ol>
			<br/>
			<input type="text" v-model="firstName2" />
			<input type="text" v-model="lastName2" />
			全名:<input type="text" v-model="fullName2"> <br/>
			<hr>
			<ul>
				<li>通过改变firstName3和lastName3来改变fullName3</li>
			</ul>
			<br/>
			<input type="text" v-model="firstName3" />
			<input type="text" v-model="lastName3" />
			全名:<input type="text" v-model="fullName3"> <br/>
		</div>
		<script type="text/javascript">
			// 阻止运行时提示
			Vue.config.productionTip = false;
			const vm = new Vue({
				// 绑定节点
				el: ".app",
				// 数据
				data: {
					name: "小奋斗",
					firstName: "小",
					lastName: "奋斗",
					// 计算属性
					firstName2: "小小",
					lastName2: "之说",
					// 简写
					firstName3: "我佛",
					lastName3: "慈悲",
				},
				// 方法
				methods:{
					fullName(){
						return this.firstName + "." + this.lastName;
					}
				},
				computed:{
					// 计算属性
					fullName2:{
						get(){
							return this.firstName2 + "." + this.lastName2;
						},
						set(value){
							console.log('set',value);
							const arr = value.split('.');
							this.firstName2 = arr[0];
							this.lastName2 = arr[1];
						}
					},
					// 简写
					fullName3(){
						return this.firstName3 + "." + this.lastName3;
					}
				}
			});
		</script>
	</body>
</html>

VUE监视属性

通过watch来响应数据的变化。

代码案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>VUE2监视属性</title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
        <!-- 
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
        -->
	</head>
	<body>
        <div id="app">
            <h3>状态变化1:</h3>
            <button @click="changeStatus1">状态</button>  {{computedStatus1}}
            <hr>
            <h3>状态变化2:</h3>
            <button @click="changeStatus2">状态</button>  {{statusName2}}
            <hr>
            <h3>状态变化3:</h3>
            <button @click="changeStatus3">状态</button>  {{statusName3}}
            <hr>
            <h3>状态变化4:</h3>
            <button @click="changeStatus4">状态</button>  {{statusName4}}
            <hr>
            <h3>深度监视,a的值是:{{numbers.a}}</h3>
			<button @click="numbers.a++">a+1</button>
            <hr>
            <h3>深度监视,b的值是:{{numbers.b}}</h3>
			<button @click="numbers.b++">b+1</button>
        </div>
        <script type="text/javascript" >
			// 阻止vue在启动时生成生产提示
			Vue.config.productionTip = false;
			// 创建Vue实例
			const vm = new Vue({
				el:'#app', 
				data:{ 
                    status1 : false,
                    statusName1: "假",
                    //
                    status2 : true,
                    statusName2: "真",
                    //
                    status3 : false,
                    statusName3: "假",
                    //
                    status4 : false,
                    statusName4: "假",
                    // 深度监视
                    numbers: { a:1, b:1 }
				},
                methods:{
                    changeStatus1(){
                        if(this.status1){
                            this.status1 = false;
                        }else{
                            this.status1 = true;
                        }
                    },
                    changeStatus2(){
                        if(this.status2){
                            this.status2 = false;
                        }else{
                            this.status2 = true;
                        }
                    },
                    changeStatus3(){
                        if(this.status3){
                            this.status3 = false;
                        }else{
                            this.status3 = true;
                        }
                    },
                    changeStatus4(){
                        if(this.status4){
                            this.status4 = false;
                        }else{
                            this.status4 = true;
                        }
                    }
                },
                computed:{
                    computedStatus1(){
                        if(this.status1){
                            return "真";
                        }else{
                            return "假";
                        }
                    }
                },
                watch:{
                    status2:{
                        // 初始化时让handler调用一下
                        immediate:true, 
                        // 当status2发生改变时,handler调用
                        handler(newValue,oldValue){
                            console.log('status2被修改了', newValue, oldValue);
                            if(newValue){
                                this.statusName2 = "真";
                            }else{
                                this.statusName2 = "假";
                            }
                        }
                    },
                    // 简写
                    status4(newValue,oldValue){
                        console.log('status4被修改了', newValue, oldValue);
                        if(newValue){
                            this.statusName4 = "真";
                        }else{
                            this.statusName4 = "假";
                        }
                    },
                    // 监视多级结构中某个属性的变化
                    'numbers.a':{
                        handler(newValue,oldValue){
                            console.log('numbers.a被改变了', newValue, oldValue);
                        }
                    },
                    // 深度监视:监视多级结构中所有属性的变化
                    numbers:{
                        deep: true,
                        handler(){
                            console.log('numbers改变了')
                        }
                    }
                }
			});
            // 第2种方法
            vm.$watch('status3',{
                immediate: false, 
                // 当status3发生改变时,handler调用
                handler(newValue, oldValue){
                    console.log('status3被修改了', newValue, oldValue);
                    if(newValue){
                        this.statusName3 = "真";
                    }else{
                        this.statusName3 = "假";
                    }
                }
            });
		</script>
	</body>
</html>

VUE绑定样式

class样式,写法:class="xxx" ,其中xxx可以是字符串、对象、数组。

1、字符串写法适用于:类名不确定,要动态获取。

2、对象写法适用于:要绑定多个样式,个数不确定,名字也不确定。

3、数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。

style样式,写法::style="{fontSize: xxx}",其中xxx是动态值;:style="[a,b]"其中a、b是样式对象。

代码案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>Vue2 class与style绑定(绑定样式)</title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
        <!-- 
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
        -->
		<style>
			.basic{
				width: 400px;
				height: 100px;
				border: 1px solid black;
			}
			.happy{
				border: 4px solid red;;
				background-color: rgba(255, 255, 0, 0.644);
				background: linear-gradient(30deg,yellow,pink,orange,yellow);
			}
			.sad{
				border: 4px dashed rgb(2, 197, 2);
				background-color: gray;
			}
			.normal{
				background-color: rgb(31, 173, 230);
			}
			.xfd1{
				background-color: yellowgreen;
			}
			.xfd2{
				font-size: 30px;
				text-shadow:2px 2px 10px red;
			}
			.xfd3{
				border-radius: 20px;
			}
		</style>
	</head>
	<body>
        <div id="app">
            <!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
			<div class="basic" :class="mood" @click="changeMood">{{name}}</div><br/> 
			<hr />
			<!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
			<div class="basic" :class="classArr">{{name}}</div> <br/>
			<hr />
			<!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用 -->
			<div class="basic" :class="classObj">{{name}}</div> <br/>
			<hr />
			<!-- 绑定style样式--对象写法 -->
			<div class="basic" :style="styleObj">{{name}}</div> <br/>
			<hr />
			<!-- 绑定style样式--数组写法 -->
			<div class="basic" :style="styleArr">{{name}}</div>
        </div>
        <script type="text/javascript" >
			// 阻止vue在启动时生成生产提示
			Vue.config.productionTip = false;
			// 创建Vue实例
			new Vue({
				el:'#app', 
				data:{
					name: '小奋斗',
					mood: 'normal',
					classArr:['xfd1','xfd2','xfd3'],
					classObj:{
						atguigu1:false,
						atguigu2:false,
					},
					styleObj:{
						fontSize: '40px',
						color:'red',
					},
					styleObj2:{
						backgroundColor:'orange'
					},
					styleArr:[
						{
							fontSize: '40px',
							color:'blue',
						},
						{
							backgroundColor:'gray'
						}
					]
				},
				methods: {
					changeMood(){
						const arr = ['happy','sad','normal']
						const index = Math.floor(Math.random()*3)
						this.mood = arr[index]
					}
				},
			});
		</script>
	</body>
</html>

相关推荐

centos7使用yum安装nginx+php7+mysql5.6

本文主要介绍安装在centos7下如何安装nginx+php+mysql的环境,centos7的版本自带安装源的版本无法实现PHP5.4以上的版本,数据库默认用的是mariadb,文章介绍的安装是如何...

Linux基础入门(VMWare中CentOS7配置yum)

上一章节,介绍了《Linux基础入门(CentOS7下通过命令行配置网络)》,本章将介绍如何配置yum源,方便后续在学习和使用的过程中,对所需工具的安装;...

CentOS 7搭建Nextcloud私有云(centos搭建云盘)

Nextcloud简介:对于私人网盘,其中最出名的就是seafile、owncloud和nextcloud。seafile是国人开发的,有免费和企业版,免费的功能有限;nextcloud是owncl...

分享一个docker镜像源地址,解决docker不能拉取的问题

自己搭建的代理,centos7只需要修改/etc/docker/daemon.json并输入以下内容:{"registry-mirrors":["https://next...

源支付5.18版全套开源源码客户端+云端+监控+协议三网免挂免输入

源支付5.18最新版协议去授权全套三端开源源码_客户端+云端+监控+协议三网免挂免输入(全套版)推荐系统为:CentOS7.6Linux系统环境:Nginx1.20.1+MySQL5.6....

centos7飞速搭建zabbix5.0并添加windows、linux监控

一、环境zabbix所在服务器系统为centos7,监控的服务器为windows2016和centos7。二、安装zabbix官方安装帮助页面...

CentOS上配置 Docker 使用代理服务器

hub.docker最近总被墙,国内大厂搞的docker镜像源代理被封被停,对于一个严重依赖一些海外项目的软件开发人员,简直没法干活了。docker要在CentOS上配置Docker使用代理服...

CentOS 7 (阿里云虚拟机) 安装 Docker

一、安装Docker1.使用root权限登录CentOS。确保yum包更新到最新sudoyumupdate...

Centos离线静默安装 oracle11g,步骤细验证成功

一、环境要求1.1.涉及工具及环境1)CentOS764位系统2)oracle安装包文件a)linux.x64_11gR2_database_1of2.zip...

Linux运维之制作指定软件包的YUM源

#挑战30天在头条写日记#关注我,不迷路,大家好,我是大王。--记录运维中遇到的故障及排查方法...

在CentOS 9 安装Nvidia显卡驱动详细操作步骤

今天给粉丝网友演示CentOS9系统下如何安装nvidia显卡驱动。·将下载好的显卡驱动放到文件夹中,这里以download为例,放入文件夹中开始对系统软件升级,是为了防止在安装显卡驱动时显示报错...

基于Linux系统的本地Yum源搭建与配置(ISO方式、RPM方式)

前言:由于公司业务服务器大部分都在内网环境下运行,内网环境无法直接使用yum安装升级更新软件,所以需要自建Yum源来满足目前日常工作需要。...

最新zabbix一键安装脚本(基于centos8)

一、环境准备注意:操作系统必须是centos8及以上的,因为我配的安装源是centos8的。并且必须连接互联网,脚本是基于yum安装的!!!...

CentOS7中使用yum安装Nginx的方法

1、添加源  默认情况Centos7中无Nginx的源,最近发现Nginx官网提供了Centos的源地址。因此可以如下执行命令添加源(...

Centos8出现Failed to download metadata for repo &#39;AppStream&#39;解决

大家都知道Centos8于2021年年底停止了服务,大家再在使用yum源安装时候,出现下面错误“错误:Failedtodownloadmetadataforrepo'AppStre...

取消回复欢迎 发表评论: