【问题标题】:How to inject Global constant to a vue component <style>?如何将全局常量注入 vue 组件 <style>?
【发布时间】:2018-08-26 06:23:06
【问题描述】:

我正在搜索如何将全局(在我的示例中为THEME_NAME)注入所有 vue 组件:

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/<%=THEME_NAME=>/bulmaswatch.scss";

    .foo {
      color: $primary;
    }
</style>

上下文:

我在我的 vue 应用程序(vue Cli 3)中使用 bulma css 的 darkly theme

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/darkly/bulmaswatch.scss";
    .foo {
        color: $primary;
    }
</style>

为了切换到cyborg 主题,我将不得不将darkly 替换为cyborg...

有没有更好的方法?类似的东西

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/<%=THEME_NAME=>/bulmaswatch.scss";

    .foo {
      color: $primary;
    }
</style>

然后在Webpack或vue.config.js的某个地方,我们可以决定主题是什么

configureWebpack: () => {
    return {
        plugins: [
            new webpack.DefinePlugin({
                THEME_NAME: "cyborg"
            }),
        ],
    }
}

【问题讨论】:

  • 我相信 DefinePlugin 只适用于 JavaScript,你必须改用 string-replace-webpack-plugin 之类的东西。可惜SASS不支持像LESS这样的动态@import语句。

标签: vue.js sass vue-component bulma


【解决方案1】:

为了切换到 cyborg 主题,我将不得不用 cyborg 到处替换黑暗...

如果您使用 re-export 模式,则不会。 webpack 不需要任何外部库和代码生成魔法。

基本上,您创建一个文件来导入您的主题。 我们暂且称它为_my-bulma-theme.scss 并导入darkly。

// _my-bulma-theme.scss
@import "bulmaswatch/darkly/bulmaswatch.scss";

在您的代码中,您导入此文件而不是直接从 Bulma 导入:

// some-component.vue
<style>
  @import "../../my-bulma-theme";
</style>

// some-other-component.vue
<style>
  @import "../../my-bulma-theme";
</style>

现在,当您想要更改主题时,您只需在一个地方进行更改:_my-bulma-theme.scss 文件。

// _my-bulma-theme.scss
@import "bulmaswatch/cyborg/bulmaswatch.scss";

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 2016-07-01
    • 2021-04-28
    • 2020-11-24
    • 2018-09-03
    • 2020-11-25
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多