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.
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.
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..
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).
Scope of SASS variables In SCSS, there are two scopes: global scope and local scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With