Subscribe on changes!

SFC CSS v-bind() not working as expected

avatar
Dec 19th 2022

Vue version

3.2.45

Link to minimal reproduction

https://sfc.vuejs.org/#eNqNkU1qwzAQha8itEkKtUSydJ1A6RVKV9rIspo4tSUxM3YpwXfvyE5ooKVkN0+a783fWT6npMbBy1JW6KBNJNDTkPYmuBiQhItdhDcLYidW4JvVkwmVXjI5hwX5PnWWPCshqqYdhess4s5I8kgvOd4YuX9lIWxKEK07ik2lOfMfZPsL2V6RSt+UZIn01eWwhBhJnLNnUWSjYu69FGNRt6FZXyd54BGmTKqfBhestu7jAHEIzT3Q9g/Iwvq29oXihc09ykfZ9ikCFb1N6oQx8NpnE3P5QCPLxTa/8V2yNvJIlLDUGt9dPtYJVYSD5kjBEKjtvfLYFzXET/TAxkZmC648yekblGKpcg==

Steps to reproduce

  1. Create SFC
  2. Assing color (as string) to variable
  3. Use v-bind to bind color to css variable in :root pseudo element
  4. Use the variable in other css class

What is expected?

I expected that css variable would be available for me to use in other classes.

What is actually happening?

CSS variable looks like its undefined and it is not working.

When you look at reproduction, you can see that I made two test classes. One with background: var(--test-color), other with background: v-bind(colorVar). The second one works properly, while the first one, which is the issue about, does not.

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (6) x64 Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz
    Memory: 3.68 GB / 15.81 GB
  Binaries:
    Node: 16.18.0 - C:\Program Files\nodejs\node.EXE
    npm: 9.2.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1266.0), Chromium (108.0.1462.54)
    Internet Explorer: 11.0.19041.1566
  npmPackages:
    vue: ^3.2.45 => 3.2.45

Any additional comments?

No response

avatar
Dec 19th 2022

Yeah that won't work because the CSS variables generated by using v-bind() in the component don't live in the :root context, so they are not accessible there. They are applied to the component's root elements, as you can see by inspecting the DOM.

This is intended behaviour so that variables do not bleed outside of the component.

avatar
Dec 19th 2022

@LinusBorg thanks for responding. Anyway, is there any official recommended method to inject variables to css from Vue SFC Javascript part?