Vue3 (3.2.x) — Vue variables in CSS (style section)

Dariusz Włodarczyk
Nerd For Tech
Published in
2 min readNov 7, 2021

--

Use case

Recently I’ve stumbled upon a problem where I’ve implemented some simple CSS based tabs. The best in it was that it “was already there”, “was free” and “worked almost out of box”. Once I was done with base case (just 2 tabs), I’ve started adding some more of them, and… things didn’t quite worked as expected.

The problem was that the SCSS code had hard-coded variable $tab-count with which all the widths, heights etc. were calculated and clickable tabs were showing & hiding content.

I didn’t wanted to have hard-coded value but rather a dynamic one, based on how many tabs are passed via prop to the Tabs component.

In the end, what I write about didn’t solved my problem but got learned about the new functionality, and case in which it won’t work.

`v-bind` in styles section

Vue 3.2.x allows to use v-bind directly in the <style> section.

Here is the simple example:

That above is literally everything that there is to be done to make it works. This also works with SCSS (alongside with vars $varName: v-bind() ).

Issue: v-bind returns string

In most cases v-bind returning string is just fine. This will probably cover 90% of cases. But it didn’t covered mine, as I needed to do loop in SCSS like that:

  • $tabCount: v-bind(tabsCount)
  • @for $i from 1 through $tabCount

This causes unavoidable error, which in my use case makes it impossible to use v-bind in style section.

--

--

Dariusz Włodarczyk
Nerd For Tech

Hobby frontend / backend developer — author of Personal Management System. https://git.io/JePh1. You can find me also here: https://ko-fi.com/volmarg.