vue2的style里面使用js变量

239 阅读1分钟

1、html

<div class="info_wrap" ref="infoWrap">
  <div class="info"> info </div>
</div>

2、css

<style>
  .info_wrap {
  	--color: '#666';
  }
  .info_wrap .info {
  	color: var(--color);
  }
</style>

3、js

<script>
export default {
    methods: {
        func(color) {
            this.$refs.infoWrap.style.setProperty('--color', color);
        }
    }
}
</script>

注意

ref必须作用在dom元素上,如果作用在自定义组件上,this.$refs.infoWrap 获取的就是组件实例,操作style会报错。