vue动态绑定class的几种方式

发布于:2024-06-21 ⋅ 阅读:(112) ⋅ 点赞:(0)

第一种  基础用法

/
<template>
  <div :class="active"></div>
</template>

<script setup>
import { ref } from "vue";
const active = ref(true);
</script>

<style></style>

第二种:三元运算法


<template>
  <div :class="isBind ? 'active' : ''">jkjkjk</div>
</template>

<script setup>
import { ref } from "vue";
const active = ref(1);
const isBind = ref(true);
</script>

<style></style>

第三种:对象法

/
<template>
  <div :class="{ actives: isActive, 'text-danger': hasError }">jkjkjk</div>
</template>

<script setup>
import { ref } from "vue";
const active = ref(true);
const isActive = ref(true);
const hasError = ref(true);
</script>

<style></style>

第四种 :数组法


<template>
  <div :class="[{ actives: isActive }, { 'text-danger': hasError }]">
    jkjkjk
  </div>
</template>

<script setup>
import { ref } from "vue";
const active = ref(true);
const isActive = ref(true);
const hasError = ref(true);
</script>

<style></style>

<tem/
<template>
  <div :class="status">jkjkjk</div>
</template>

<script setup>
import { ref, computed } from "vue";
const status = ref(["bold", "highlight"]);
</script>

<style></style>

第五种 :计算属性法

/
<template>
  <div :class="dynamicClass">jkjkjk</div>
</template>

<script setup>
import { ref, computed } from "vue";
const active = ref(true);
const isActive = ref(true);
const hasError = ref(true);

const ClassName = ref("");
const dynamicClass = computed(() => ({
  active: isActive.value,
  inactive: !isActive.value,
}));
</script>

<style></style>

第六种:方法

/
<template>
  <div :class="dynamicClass()">jkjkjk</div>
</template>

<script setup>
import { ref, computed } from "vue";

const isActive = ref(true);

const dynamicClass = () => ({
  active: isActive.value,
  inactive: !isActive.value,
});
</script>

<style></style>

****tips:

虽然方法和计算属性得到的结果一样  还是要多使用计算属性 ?

方法和计算属性在Vue3中都可以用于处理和操作数据,但它们在使用和性能上有一些关键的区别。计算属性是一种具有缓存机制的响应式对象,只有当其依赖的数据发生变化时才会重新计算。而方法没有缓存机制,每次页面更新时都会重新执行,无论数据是否变化。


网站公告

今日签到

点亮在社区的每一天
去签到