简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM