vue基础-动态设置样式class和style

动态设置样式class和style

一. :class

  1. 语法:
class="{类名: 布尔值, 类名2: 布尔值}"
  1. 作用: 动态设置class
  2. 代码示例
<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

  1. 语法:
:style="{ 样式属性: 样式的值}" 
  1. 样式属性如果有-连字符, 可以用驼峰命名方式, 也可以加引号
 'font-size':'20px' 
 fontSize: '20px'
  1. 代码示例
<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>

猜你喜欢

转载自blog.csdn.net/qq_41421033/article/details/124992856