龙空技术网

动态:class和:style绑定

俊哥前端工程师 64

前言:

目前各位老铁们对“vue怎么给class添加样式”大概比较关切,姐妹们都需要剖析一些“vue怎么给class添加样式”的相关知识。那么小编也在网络上搜集了一些有关“vue怎么给class添加样式””的相关文章,希望各位老铁们能喜欢,小伙伴们快快来学习一下吧!

1. 在应用界面中, 某个(些)元素的样式是变化的

class/style绑定就是专门用来实现动态样式效果的技术

2. 动态class绑定

:class=等号后的变量值 可以是字符串

:class=等号后 可以是对象

:class=等号后 可以是数组

3. 动态style绑定

:style="{ color: myPinkColor, fontSize: fontSize + 'px' }"

:style="{color: myPinkColor, fontSize: (fontSize > 8 ? fontSize : 10) + 'px'}

:style="{对象左边是css样式名: 右边是动态绑定的值 }

<template>  <div style="font-size: 14px;">    <h2>1. class绑定</h2>    <!-- 变量值可以写一个或多个class名 -->    <p class="text-center" :class="myClassAll">1个或多个class名</p>     <!-- class类名: 冒号右边的值如果为true则添加该类名,false则没有该类名 -->    <p :class="{'bg-pink': hasBgPink, 'color-fff': hasColorFff }"> :class=绑定方式是对象</p>    <p :class="['bg-pink', hasColorFff ? 'color-fff' : 'color-000' ]"> :class=绑定方式是数组</p>     <h2>2. style绑定</h2>    <p style="color:red; font-size: 30px">静态的style</p>    <p :style="{color: myPinkColor, fontSize: (fontSize > 8 ? fontSize : 10) + 'px'}">动态的style</p>    <!-- 点击更新动态绑定的class 和 style样式 -->    <button @click="updateClassStyle">更新</button>  </div></template><script lang="ts">// vue3.0版本语法import { defineComponent, ref, } from 'vue';export default defineComponent({  name: "组件名",  setup() {    const myClassAll = ref('bg-pink color-fff')    const hasBgPink = ref(true)    const hasColorFff = ref(true)    const myPinkColor = ref('pink')    const fontSize = ref(10)    const updateClassStyle = () => {      // 动态更新class类名      hasBgPink.value =!hasBgPink.value      hasColorFff.value =!hasColorFff.value      // 动态更新style样式      myPinkColor.value = 'blue'      fontSize.value = 60    }    return {      myClassAll,hasBgPink,updateClassStyle,      hasColorFff,myPinkColor,fontSize    }  },});</script><style scoped>.text-center {  text-align: center;}.bg-pink {  background-color: pink;}.color-fff {  color: #fff;} .color-000 {  color: #000;}</style>

页面显示效果:

点击更新按钮后的效果:

如果你想了解更多关于前端开发的内容,不妨关注我的原创文章。我会不定期更新,为你带来最新的前端技术和知识。感谢你的关注和支持,期待与你一同探索前端开发的奇妙世界!

标签: #vue怎么给class添加样式 #style在html