组件中通过:before(伪类)给文字前面加样式-vue

11 篇文章 0 订阅
1 篇文章 0 订阅

要求实现效果:
在这里插入图片描述

如果不是组件内使用把props中传的参数改为data中挂载即可
实现方案1.

 <div class="status">
    <div class="outer-circle" :style="{'margin-left':left}">
      <span :class="colorClass"></span>
      <span>{{ text }}</span>
    </div>
  </div>
  export default{
  data () {
  return {
  colorClass: ''
  }}
  props: {
    text: {
      type: String,
      required: false,
      default: ''
    }
  }
  }
<style>
.circle{
  width: 8px;
  height: 8px;
  margin-right: 0.3em;
  border-radius: 50%;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  &.yellow{
    background: $yellow;
  }
  &.green{
    background: $green;
  }
  &.blue{
    background-color: $blue;
  }
  &.red{
    background-color: $red;
  }
  &.gray{
    background-color: $gray;
  }
}
</style>

在状态前面加入一个div去盛放这个有颜色的⚪

性能不好,会形成很多没必要的div块而且形成的dom树比较复杂以后修改的话不好修改

下面有一种更好的方法

实现方案2.


<span :class="colorClass">{{ text }}</span>

export default {
 data () {
  return {
  text : ''
  }}
  props: {
  text: {
  type: String,
   required: false,
      default: ''
  },
    colorClass: {
      type: String,
      required: false,
      default: '',
		// 校验规则
      validator: function (value) {
        const colorList = ['red', 'green', 'yellow', 'blue', 'gray', '']
        return colorList.indexOf(value) > -1
      }
    }
  }
}
<style>
.red, .green, .yellow, .blue, .gray{
  padding-left:20px;
  position: relative;
  &:before{
    content: '';
    left:0.5em;
    top: 0.5em;
    position:absolute;
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
  }
}
.red:before{
  background-color:$red;
}
.green:before{
  background-color:$green;
}
.yellow:before{
  background-color:$yellow;
}
.blue:before{
  background-color:$blue;
}
.gray:before{
  background-color:$gray;
}
</style>

先用padding-left给⚪腾一个位置,然后通过伪类的width,height创建出一个⚪,把它直接定位到文字前面的空间里,

然后再通过colorClass动态控制它的颜色

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人间清醒小仙女

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值