0
votes

I have configured sass using this link https://cli.vuejs.org/guide/css.html#referencing-assets Installed npm install -D sass-loader sass

created variables.scss under src

src/variables.scss

$primary: red;

created and configured vue.config.js in root folder

project-folder/vue.config.js

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "~@/variables.sass"`,
      },
    },
  },
};

now, in below vue file I am trying to access variable declared in variables.scss file. But this is throwing error '$primary' is not defined.

src/components/HelloWorld.vue

<template>
  <div>
    <h1>Hello world</h1>
  </div>
</template>
<script>
export default {
  mounted(){
    console.log('mounted',$primary) // error: '$primary' is not defined, how to fix this ?

  }
}
</script>

How to use $primary in HelloWorld.vue file methods in mounted or any other functions in a .vue file ?

here is my package.json

package.json

{
  "name": "sass-vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.4",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.3.0",
    "@vue/cli-plugin-eslint": "~4.3.0",
    "@vue/cli-service": "~4.3.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "^1.26.5",
    "sass-loader": "^8.0.2",
    "vue-template-compiler": "^2.6.11"
  }
}
1

1 Answers

0
votes

According to docs you should be able to access variable in style tags not in javascript.

<template>
  <div>
    <h1>Hello world</h1>
  </div>
</template>

<script>
  export default {
    mounted(){
    }
  }
</script>

<style lang="scss">
  div h1 {
    background-color: $primary;
  }
</style>