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.

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.