zl程序教程

您现在的位置是:首页 >  后端

当前栏目

在vue2的style标签中使用css变量

变量CSS 使用 标签 Vue2 Style
2023-06-13 09:11:18 时间

前两天有一个更换主题需求,想将系统主题包括hover颜色都更换

代码如下:

<template>
  <!-- 需要绑定style -->
  <div class="hello" :style="css">
    <h1>{{ msg }}</h1>
    <p>
      For a guide and recipes on how to configure / customize this project,<br>
      check out the
      <a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
    </p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      themeColor: 'red'
    }
  },
  mounted() {
    setInterval(() => this.themeColor = "rgb(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 10) + ')', 100)
  },
  computed: {
    css() {
      const { themeColor } = this
      return {
        '--theme-color': themeColor
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
a {
  color: #42b983;
  transition: color 100ms;
}

a:hover {
  color: var(--theme-color)
}
</style>

可以试着把鼠标移动上去,会随机变色