在实际开发中会遇到根据不同的状态显示不同的样式的情况,这个时候写在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>