class类和style内联样式的绑定 + 事件处理 + uniapp创建自定义页面模板

发布于:2025-07-07 ⋅ 阅读:(21) ⋅ 点赞:(0)

目录

一.class类的绑定

1.静态编写

2.动态编写

二.style内联样式的绑定

三.事件处理

1.案例1

2.案例2

四.uniapp创建自定义页面模板

1.为什么要这么做?

2.步骤

①打开新建页面的界面

②在弹出的目录下,新建模板文件

③用HBuilderX打开该模板文件,填写代码,并保存文件

④下次创建页面时,直接创建该模板页面即可,就能直接生成一个页面的基础代码


一.class类的绑定

1.静态编写

代码:

<template>
	<view>
		<button class="btn01 moreCss">更换样式</button>
	</view>
</template>
 
<script setup>

</script>
 
<style lang="scss">
.btn01{
	height:100px;
	width:100px;
}
.moreCss{
	background:pink;
}
 
</style>

运行效果:

可见此时button元素,同时应用了btn01和moreCss这两个Css样式

2.动态编写

代码:

<template>	
	<view>
		<button class="btn01" :class="isShow?'moreCss':''" @click="changeCss">更换样式</button>
	</view>
</template>
 
<script setup>
import {ref} from 'vue';
const isShow = ref(false);

const changeCss = () => {
	isShow.value = !isShow.value;
}
</script>
 
<style lang="scss">
.btn01{
	height:100px;
	width:100px;
}
.moreCss{
	background:pink;
}
</style>

运行效果:

点击一下这个按钮,就会发生样式的变化:

代码解读:

当我们点击按钮时,会让isShow这个变量的值,从true/false之间切换,进而影响:class="isShow?'moreCss':''"这个三元表达式的值。

:class就是v-bind:class的简写,让class可以动态赋值。

二.style内联样式的绑定

三.事件处理

1.案例1

代码:

<template>
	<view style="height:100px;width:100px;background: pink;" @click="addOne">
		{{ num }}
	</view>
</template>
 
<script setup>
import {ref} from 'vue';

const num = ref(0);
const addOne = () => {
	num.value++;
}
</script>
 
<style lang="scss">
</style>

运行效果:

2.案例2

代码:

<template>
	<switch @change="onChange"/>
	<button type="primary" :loading="isLoading">我的按钮</button>
</template>
 
<script setup>
import {ref} from 'vue';
const isLoading = ref(false);
//切换switch开关,触发的事件
const onChange = (e)=> {
	console.log(e.detail.value);//e.detail.value代表开关的状态,值:true/false
	isLoading.value = e.detail.value;
}
</script>
<style lang="scss">
</style>

运行效果:

四.uniapp创建自定义页面模板

1.为什么要这么做?

因为以后使用uniapp写项目,当创建页面时,就可以直接创建页面模版,里面包含了基本代码。

2.步骤

①打开新建页面的界面

②在弹出的目录下,新建模板文件

③用HBuilderX打开该模板文件,填写代码,并保存文件

④下次创建页面时,直接创建该模板页面即可,就能直接生成一个页面的基础代码

可见此时,直接通过模板生成了该页面文件的基础代码。还是十分方便的!

以上就是本篇文章的全部代码,喜欢的话可以留个免费的关注呦~~