vue:css使用data中的变量

如果要在css中使用变量,需要借助setProperty函数:

<template>
  <div class="home" ref="UI">
    <div class="header">hello world</div>
  </div>
</template>
 
<script>
export default {
  data () {
    return {
      color: 'red'
    }
  },
  mounted () {
    this.setUI()
  },
  methods: {
    setUI () {
      this.$refs.UI.style.setProperty('--color', this.color) // 算是定义css变量并赋值
    }
  }
}
</script>
<style lang="scss" scoped>
.home {
  width: 200px;
  height: 100px;
  border: 1px solid #ccc;
  text-align: center;
  margin: 10px auto;
  .header {
    color: var(--color); // 使用css变量
    padding-top: 20px;
  }
}
</style>

效果图:

 

 

 

转: https://blog.csdn.net/qq_37899622/article/details/120546933

 

posted @ 2022-04-22 16:47  与f  阅读(1269)  评论(0编辑  收藏  举报