SCSS使用变量动态修改elmentUI元素样式

发布于:2024-07-03 ⋅ 阅读:(19) ⋅ 点赞:(0)

需求

面包屑el-breadcrumb的样式要随主题色的变更而改变,图如下
在这里插入图片描述
主题色设置
在这里插入图片描述

实现

主题色的变化会把当前色存储到store的theme上,面包屑只要引用store的theme即可,现在的问题是在scss的样式里面如何引用store的theme变量呢?

一波网上冲浪后找到以下解决方法:

vue的template使用style定义变量:

关键代码::style="{'--theme-color': ${theme}}"

<el-breadcrumb class="app-breadcrumb" separator="/" :style="{'--theme-color': `${theme}`}">

JS引入store的theme变量

computed: {
  theme () {
    return this.$store.state.settings.theme
  }
}

SCSS使用上面style定义的变量--theme-color,使用方法var(--theme-color)

::v-deep .el-breadcrumb__inner a {
  font-weight: bold !important;
  color: var(--theme-color);
}

完整的代码如下:

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/" :style="{'--theme-color': `${theme}`}">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span
          v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
          class="no-redirect"
        >{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
export default {
  data () {
    return {
      levelList: null
    }
  },
  computed: {
    theme () {
      return this.$store.state.settings.theme
    }
  },
  watch: {
    $route (route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created () {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb () {
      // only show routes with meta.title
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]

      // 首页不显示
      this.levelList = []

      // 拼接面包屑
      if (!this.isDashboard(first)) {
        matched = [{
          path: '/index', meta: { title: '首页' }
        }].concat(matched)

        this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
      }
    },
    isDashboard (route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim() === 'Dashboard'
    },
    handleLink (item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(path)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #ffffff;
    font-weight: bold;
    cursor: text;
  }
}

::v-deep .el-breadcrumb__separator {
  color: #ffffff;
}

::v-deep .el-breadcrumb__inner a {
  font-weight: bold !important;
  color: var(--theme-color);
}

::v-deep .el-breadcrumb__inner a:hover {
  color: #ffffff;
}
</style>

实现效果(可以看到面包屑中“首页”的颜色会随主题色的变化而变化)

在这里插入图片描述