:class的用法及应用
参考小满视频
在同一个标签中,class只能有一个,:class也只能有一个
:class的用法
1. :class = “非响应式的变量”(一般不使用,和写死了一样)
const a = "style1"
<span :class="a"></span>
浏览器中:
2. :class = “响应式对象”
const a = ref("style2")
<span :class="a"></span>
浏览器源码:
3. :class = “{对象形式}”
- 可以有多个类名
- 因为有{}包裹,所以称为对象形式,本质不是
<span :class="{ style3: 1 == 1 }"></span>
- class中的style3有没有,取决于后面的计算结果,结果为true则有,flase则没有
浏览器源码:
4. :class=“[类名1,类名2]”
建议使用这种形式
- 可以是1个或者多个类名
- 类名可以是响应式对象
- 还可以三目运算
- 目的:可以有多个类名
const a = ref("style4")
const b = ref("style5")
<span :class="[a,b]"></span>
浏览器源码:
- 优点:可以使用三目运算符
const a = ref("style4");
const b = ref("style5");
const c = ref("style6");<span :class="[1 == 1 ? a : b, c]"></span>
浏览器源码:
实际中的应用
- 实现标签切换
代码中重要的地方
- 通过
:class
实现类的添加和删除,达到切换样式的效果- 动态组件
<component :is="组件名字"></component>
父组件代码:
父组件App.vue
<template><component :is="whichVue"></component><!-- active:当前选中的标签的索引,被选中时的样式--><span:class="[active === index ? 'active' : '']"class="vueTitle"@click="chooseVue(item, index)"v-for="(item, index) in data">{{ item.name }}</span><!-- 动态组件,由is的值来决定<component>的位置渲染哪一个的组件 --></template><script setup lang="ts">
import { ref,shallowRef } from "vue";
import SonA from "./components/A.vue";
import SonB from "./components/B.vue";
import SonC from "./components/C.vue";// 动态组件is的值
const whichVue = shallowRef(SonA);
// 点击选择标签后,active表示被选中标签的索引
const active = ref(0);
// 点击事件:标签被点击后,更新whichVue和active的值
const chooseVue = (item: { name: string; com: any }, index: number) => {whichVue.value = item.com;active.value = index;
};
// 把子组件的名字和组件绑定在一起
const data = shallowRef([{name: "A组件",com: SonA,},{name: "B组件",com: SonB,},{name: "C组件",com: SonC,},
]);
</script><style lang="scss">
.active {background-color: blue;
}
.vueTitle {margin: 10px;padding: 5px 10px;border: 1px solid #ccc;cursor: pointer;
}
</style>
子组件A的代码:
<template><div class="com">子组件A.vue的内容</div>
</template><script setup lang="ts"></script><style scoped lang="scss">
@import "../style.scss";
.com{@include sonVueStyle;
}
</style>
子组件B的代码
<template><div class="com">子组件B.vue的内容</div>
</template><script setup lang="ts">
</script><style scoped lang="scss">
@import "../style.scss";
.com {@include sonVueStyle;
}
</style>
子组件C的代码:
<template><div class="com">子组件C.vue的内容</div>
</template><script setup lang="ts"></script><style scoped lang="scss">
@import "../style.scss";
.com{@include sonVueStyle;
}
</style>
子组件的样式:
@mixin sonVueStyle{height:100px;border:2px solid #ccc;font-size:20px;display: flex;justify-content:center;align-items: center;width: 300px;margin: 10px;
}