vue组件动态添加类、动态添加样式

29 阅读1分钟

动态类

<template>
    <p class="top"">静态类</p>
    <p :class="{ bottom: match }">动态类</p>
</template>
<script setup lang="ts">
    const match = ref(true)
</script>
<style lang="stylus" scoped>
  .top {
  }
  .bottom {
  }
</style>

动态样式

解决class中不能使用变量的问题

<template>
    <p style="background: red">静态样式</p>
    <p :style="{background: color?.replace(')',',0.1)')}">动态样式1</p>
    <p :style="computedStyle">动态样式2</p>
</template>
<script setup lang="ts">
  const props = defineProps({
    color: {
      type: String,
      default: ''
    },
  })
  
  const computedStyle = computed(() => {
  const { color } = props
  return {
    background: color?.replace(')',',0.1)') //可对参数进行处理
  }
})
</script>