Vue使用v-bind动态定义css

73 阅读1分钟

CSS 中的 v-bind()

单文件组件的 <style> 标签支持使用 v-bind CSS 函数将 CSS 的值链接到动态的组件状态:

<template>
  <div class="text">hello</div>
</template><script>
export default {
  data() {
    return {
      color: 'red'
    }
  }
}
</script><style>
.text {
  color: v-bind(color);
}
</style>

这个语法同样也适用于 ``,且支持 JavaScript 表达式 (需要用引号包裹起来):

<script setup>
const theme = {
  color: 'red'
}
</script><template>
  <p>hello</p>
</template><style scoped>
p {
  color: v-bind('theme.color');
}
</style>

实际的值会被编译成哈希化的 CSS 自定义属性,因此 CSS 本身仍然是静态的。自定义属性会通过内联样式的方式应用到组件的根元素上,并且在源值变更的时候响应式地更新。

因此我们在写组件时候可以如下

<template>
  <div class="bannerbox pb-8">
    <ClientOnly>
      <template #fallback>
        <div class="flex items-center justify-center" style="background: #eee;padding:40px 0;">
          <k-loading show></k-loading>
        </div>
      </template>
      <n-carousel show-arrow autoplay :interval="duration"  v-if="bannerList && bannerList.length >0">
        <template v-for="(item) in bannerList" :key="item.cover">
          <nuxt-link :to="item.skipValue" :target="item.openMark" :title="item.skipTitle">
            <img
                class="carousel-img"
                :src="item.cover"
            >
          </nuxt-link>
        </template>
      </n-carousel>
    </ClientOnly>
  </div>
</template>
<script setup>
var bannerList = ref([])
// 自定义属性
const props = defineProps({
  height: {
    type: Number,
    default: 150
  },
  duration: {
    type: Number,
    default: 5000
  }
})
​
</script>
<style scoped>
.carousel-img {
  width: 100%;
  height: v-bind(props.height+ 'px');
  object-fit: cover;
}
</style>