效果
源代碼
<template>
<div class="divClass">
<!-- 使用集合形式,style則對應集合,當前可應用於redClass中 -->
<div :style="divStyle" class="redClass"></div>
<!-- 使用單個變量,style則對應單個, 當前可應用於blueClass中-->
<div :style="{'--blueColor': blueColor}" class="blueClass"></div>
</div>
</template>
<script>
export default {
data() {
return {
//創建divStyle對象集合
divStyle: {
"--redColor": "red"
},
// 創建單個樣式變量
blueColor: "blue"
};
}
};
</script>
<style lang="scss" scoped>
// 畫一個藍圈圈
.blueClass {
border: 1px solid var(--blueColor);
border-radius: 50%;
width: 40px;
height: 40px;
border-radius: 50%;
line-height: 40px;
text-align: center;
color: #fff;
}
// 畫一個紅圈圈
.redClass {
border: 1px solid var(--redColor);
border-radius: 50%;
width: 40px;
height: 40px;
border-radius: 50%;
line-height: 40px;
text-align: center;
color: #fff;
}
.divClass {
display: flex;
margin-top: 10%;
justify-content: space-evenly;
}
</style>
解說
- 在vue中我們需要抽離變量當樣式,我們使用變量來進行操作
- 綁定style樣式,我們就可以在class中進行賦值了
- 如果綁定了集合,我們則直接使用var(key值) 即可
- 如果綁定了變量,我們則在綁定的style中創造集合,將變量當value值放進去即可, 在style中和3一樣的哦,都要使用var(key值)