9

I've recently started using Vue.js 2, and I'm a fan of the single-file component structure:

<template>
  <h1>Hello World</h1>
</template>


<script>
export default {
  name: 'hello-world',
};
</script>


<style scoped lang="scss">
h1 {
  font-size: 72px;
}
</style>

I'm curious if there's an established way to pass variables between SCSS and JS, though. I need to share a value, and right now it's duplicated in both sections.

I used the Vue CLI to create this project, so it's being bundled with Webpack 2, using the vue-loader. I'm hoping there's a way to configure it to populate variables from JS to SCSS, or vice-versa.

Joshua Comeau
  • 2,594
  • 24
  • 25
  • 1
    I can't offer specific insight into [tag:scss], but [tag:css-variables] have JavaScript setters and getters; use of which is shown in the following answers: http://stackoverflow.com/a/36088890/82548 and http://stackoverflow.com/a/16943843/82548 (disclaimer: the second answer is one of my own). – David Thomas Feb 28 '17 at 13:00
  • Thanks David! Yeah, I'm hoping that there's a way with vue-loader, to handle it during the bundle process. – Joshua Comeau Feb 28 '17 at 13:05

1 Answers1

4

Your question would benefit from more details. How thorough of an integration do you need? There's this which would allow you to create a JSON file and get those values as SCSS variables as well as JS (obviously).

https://github.com/Updater/node-sass-json-importer

If you want something more simple you can also create inline styles by using :style. That way it would be dynamic.

So something like:

<div :style="{ height: heightInPixels }">...</div>

Here's a quick demo of it: https://jsfiddle.net/4s25kca2/

It really depends on your exact need.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
  • Hey Bill, thanks for your time. So yeah, I'm familiar with the techniques you mention, I was just hoping there was a method in Vue-loader (or an associated plugin) I was missing. Specifically, I'm setting an element's opacity dynamically based on scroll position (to fade it in). I wound up reading this value straight from the DOM via getBoundingClientRect; it's not as elegant a solution, but it works just fine. – Joshua Comeau Feb 28 '17 at 20:44