uniapp中scss如何使用js变量

4,140 阅读1分钟

常规方法如下

<template>
  <!-- css 使用 js变量 -->
  <view class="homepage" :style="[fsObj]">
    <view class="name">hello world</view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        fsObj: { // fs对象
          '--red': 'red'
        }
      };
    },

    created() {
      // 通过修改 fsObj对象 切换关怀模式
      setTimeout(() => {
        this.fsObj =  {
          '--red': 'blue'
        };
      }, 3000);
    }
  }
</script>

<style scss>
  .homepage {
    .name {
    	color: var(--red);
    }
  }
</style>

编译前处理模式如下 在vue.config.js中

const fs = require('fs-extra');
const StylelintWebpackPlugin = require('stylelint-webpack-plugin');

class WritePlugin {
	apply(compiler) {
		compiler.hooks.done.tap('funWrite plugin', compilation => {
			this.funWrite();
		});
	}

	// 写入函数
	funWrite() {
		// 常量配置路径
		const constantsPath = `src/common/utils/constants.js`;
		// 颜色配置文件路径
		const colorJsPath= './src/common/style/color.js';
		// 目标color.scss路径
		const colorScssPath = 'src/common/style/color.scss';

		if (fs.existsSync(constantsPath)) {
			// 读取常量配置文件
			let ast = fs.readFileSync(constantsPath, 'utf-8');
			// 使用正则筛选常量
			const match = ast.match(/\nexport\s*const\s*MY_ID\s*=\s*([^;]+)/);
			let myId = match ? match[1] : "'default'";
			// 我的ID
			myId = myId.split("'")[1];
			// 颜色配置项
			const colorJsObj = require(colorJsPath);
			// 颜色配置项中含有当前 ? 当前 : 默认
			myId = colorJsObj.hasOwnProperty(myId) ? myId : 'default';

			// 目标color.scss中的id
			let lastId = fs.readFileSync(colorScssPath, 'utf-8').split('^^');
			lastId = lastId.length ? lastId[1] : '';

			// 如果id改变了
			if (myId !== lastId) {
				// 读取颜色配置文件
				// 写入文件
				fs.writeFileSync(colorScssPath, colorJsObj[myId], 'utf-8');
			}
			console.log(`==================== success ====================`);
			console.log(fs.readFileSync(colorScssPath, 'utf-8'));
			console.log(`=============== ${new Date().toLocaleString()} ===============`);
		}
	}
};

module.exports = {
	devServer: {
		port: 7999,
		// proxy: {
		// 	'': {
		// 		target: '',
		// 		changeOrigin: true,
		// 		pathRewrite: {
		// 			'^': ''
		// 		}
		// 	}
		// }
	},
	configureWebpack: {
		// watchOptions: {
		// 	ignored: [
		// 		'src/common/utils/constants.js',
		// 		'src/common/style/color.scss'
		// 	]
  	//   },
		plugins: [
			new StylelintWebpackPlugin({
				files: ['**/*.{html,vue,css,sass,scss}'],
				fix: false,
				emitErrors: true,
				failOnError: true
			}),

			// 写入插件
			new WritePlugin()
		]
	}
};

color.js

module.exports = {
  'default': `// ^^default^^默认颜色
$main: red;
$main1: blue;
$main2: green;
$main3: #ddebff; // 这是一个注释
`,
  'aaaaaaaaaa': `// ^^MY1002^^编号1001
$main: red;
$main1: blue;
$main2: green;
$main3: #ddebff; // 这是一个注释
`,
  'bbbbbbbbbb': `// ^^MY1002^^编号1002
$main: yellow;
$main1: blue;
$main2: green;
$main3: #ddebff; // 这是一个注释
`,
}

color.scss

// ^^1001^^编号1001
$main: red;
$main1: blue;
$main2: green;
$main3: #ddebff; // 这是一个注释

constants.js

// MY1001
// export const MY_ID = 'aaaaaaaaaa';

// MY1002
export const MY_ID = 'bbbbbbbbbb';

uni.scss

$main: red;
$main1: blue;
$main2: pink;
$main3: black;

// 注意在默认配置文件下面引入(防止此处不生效)
@import "@/common/style/color.scss";

$grey1: #f4f5f7;
$grey2: #dfe1e6;