Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 564
Joshua Comeau Avatar asked Feb 28 '17 12:02

Joshua Comeau


People also ask

Can you use SCSS variables in JS?

To make Sass (or, specifically, SCSS in this case) variables available to JavaScript, we need to “export” them. The :export block is the magic sauce webpack uses to import the variables. What is nice about this approach is that we can rename the variables using camelCase syntax and choose what we expose.

How do I run a variable from another file in SCSS?

To use variables across multiple files in SASS is carried out by @import rule of SASS. @import rule which import Sass and CSS stylesheets for providing variables, @mixins and functions. Such that combine all stylesheets together for compiled css. It also imports URL such as frameworks like Bootstrap etc..

How do I add SCSS to Vue command line?

You have SCSS variables in one file that you want to make available to your Vue components. The good news is that the Vue CLI makes it incredibly easy to support writing SCSS, and with Vue's single file components you can simply add lang="scss" to the <style> block (docs).

Are SCSS variables scoped?

Scope of SASS variables In SCSS, there are two scopes: global scope and local scope.


1 Answers

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.

like image 140
Bill Criswell Avatar answered Sep 21 '22 19:09

Bill Criswell