在样式中使用组件中接收的参数

Published on
8

在使用vue开发时,经常会封装很多的组件方便复用,那么难免就有写样式相关组件,比如需要使用时传入颜色、高度等样式参数。

那么问题来了:我们要怎么在样式中使用组件中接收的参数呢?或者说,我们要怎么在样式中使用data中的变量呢?

参考代码

<template>
  <div class="box" :style="styleVar">
  </div>
</template>
<script>
export default {
  props: {
    height: {
      type: Number,
      default: 54,
    },
  },
  computed: {
    styleVar() {
      return {
        '--box-height': this.height + 'px'
      }
    }
  },
}
</script>
<style scoped>
.box {
  height: var(--box-height);
}
</style>

这样我们就在vue中实现了在样式里使用js变量的方法:

通过css定义变量的方式,将变量在行内注入,然后在style中使用var()获取我们在行内设置的数据即可。


0