动态设置样式class和style
一. :class
- 语法:
class="{类名: 布尔值, 类名2: 布尔值}"
- 作用: 动态设置class
- 代码示例
<template>
<div>
<button
:class="{ grey: isOn === true, white: isOn === false }"
@click="isOn = !isOn"
>
开关
</button>
</div>
</template>
<script>
export default {
data() {
return {
isOn: false };
},
methods: {
},
};
</script>
<style>
.grey {
background-color: #111;
}
.white {
background-color: white;
}
</style>
二. :style
- 语法:
:style="{ 样式属性: 样式的值}"
- 样式属性如果有-连字符, 可以用驼峰命名方式, 也可以加引号
'font-size':'20px'
fontSize: '20px'
- 代码示例
<template>
<div>
<button
:style="{ background: isOn ? 'grey' : 'white', 'font-size': '20px' }"
@click="isOn = !isOn"
>
开关
</button>
</div>
</template>
<script>
export default {
data() {
return {
isOn: false,
};
},
methods: {
},
};
</script>
<style>
.grey {
background-color: #fff;
}
.white {
background-color: #000;
}
</style>