首页 > 解决方案 > vue单文件组件导入scss intellisense

问题描述

我正在玩 VSCode 和 vue。我可以通过 import 语句在 vue sfc 中使用带有一些变量的外部 scss 文件。一切正常,除了智能感知不加载 .vue 文件中的变量。

这是我在 .vue 文件中的样式标签

<style lang="scss" scoped>
@import '~styles/main';
$other-color: #FFAAAA;
.greeting {
    font-size: 20px;
    color: $secondary-color;
    border-bottom: 2px solid $primary-color;
    margin-bottom: 15px;
}
</style>

$other-color 是由 intellisense 找到的,但不是在 '~styles/main' 中定义的 $primary-color 和 $secondary-color (并由 webpack 正确加载)。

我是否遗漏了某些东西,或者无法使其工作?

标签: vue.jssassvisual-studio-codeintellisense

解决方案


在玩了一点之后,我得出了这个解决方案。我首先创建了一个单独的 .scss 文件,将所有组件样式移到那里,然后在我的 vue sfc 文件中添加了对组件 scss 的引用。

<!-- .vue -->
<template>
<div>
    <div class="greeting">Hello {{name}}{{exclamationMarks}}</div>
    <button @click="decrement">-</button>
    <button @click="increment">+</button>
</div>
</template>

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
    props: ['name', 'initialEnthusiasm'],
    data() {
        return {
            enthusiasm: this.initialEnthusiasm,
        }
    },
    methods: {
        increment() { this.enthusiasm++; },
        decrement() {
            if (this.enthusiasm > 1) {
                this.enthusiasm--;
            }
        },
    },
    computed: {
        exclamationMarks(): string {
            return Array(this.enthusiasm + 1).join('!');
        }
    }
});
</script>

<style src="./Hello.scss" scoped></style>

通过这种方式,我可以毫无问题地使用导入的 scss 文件中的变量。

在这个例子中,问候类是在 Hello.scss 文件中定义的。为了在我的 vue 文件中自动完成 scss 类,我使用了这个Visual Studio 代码扩展。

如果您有更好的解决方案,请分享。


推荐阅读