Joshua Comeau Joshua Comeau -4 years ago 285
Sass (Sass) Question

Shared variables between JS and SCSS in Vue

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download