vue 在scss中使用js变量值

9 篇文章 1 订阅

在实际开发中会遇到根据不同的状态显示不同的样式的情况,这个时候写在style标签中要是能获取到js变量之后那就方便了很多。

1、在scss中使用js变量值(使用v-bind双向绑定):

<template>
	<div class="content" :style="{'--color': themeColor}">
		<div class="title">这是一个标题</div>
	</div>
	<button @click="themeColor='pink'">修改颜色</button>
</template>

<script>
	export default {
		name: 'DEMO',
		data() {
			return {
				themeColor: 'red'
			}
		},
	}
</script>

<style lang="scss">
	.content {
		// --color 在content及其子元素都可以使用
		width: 100%;
		height: 200px;
		background-color: var(--color);

		.title {
			background-color: white;
			color: var(--color);
		}
	}
</style>

2、变量在style标签定义,在js进行修改:

<template>
	<div class="content" ref="content">
		<div class="title">这是一个标题</div>
	</div>
	<button @click="changeBgColor">修改背景颜色</button>
	<button @click="changeFontColor">修改字体颜色</button>
</template>

<script>
	export default {
		name: 'DEMO',
		data() {},
		methods: {
			changeBgColor() {
				document.getElementsByTagName('body')[0].style.setProperty('--bg-color', 'pink');
			},
			changeFontColor() {
				// --font-color 在哪个元素定义的就在哪个元素修改
				this.$refs.content.style.setProperty("--font-color", 'pink');
			}
		},
	}
</script>

<style lang="scss">
	// --bg-color:为js操作此变量需要用到的KEY
	// --red:默认css属性值
	$themeBgColor: var(--bg-color, red);

	.content {
		--font-color: red;
		width: 100%;
		height: 200px;
		background-color: $themeBgColor;

		.title {
			background-color: white;
			color: var(--font-color);
		}
	}
</style>

3、Vue3可以直接使用v-bind绑定

<template>
	<div class="content" ref="content">
		<div class="title">这是一个标题</div>
	</div>
	<button @click="changeBgColor">修改背景颜色</button>
</template>

<script>
	export default {
		name: 'DEMO',
		data() {
			return {
				themeColor: 'red'
			}
		},
		methods: {
			changeBgColor() {
				this.themeColor = 'pink';
			},
		}	
	}
</script>

<style lang="scss">
	.content {
		width: 100%;
		height: 200px;
		background-color: v-bind('themeColor');
	}
</style>

  • 12
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值