基础/类与样式绑定

标签的 class 和 style 也属于 attribute,因此可以通过 v-bind 指令进行绑定。

先来复习一下 Vue 的指令:

v-baz:value.foo="bar"

前缀 v- ,指令名称 baz,参数是 : 后面的 value ,赋值是一个表达式 bar 回去找名称为 bar 的变量,修饰符是 foo

绑定HTMl class

html 复制代码
<div :class="[
  'base-class',
  ...classObj,
  { active: isActive },
  otherClass
]" ></div>

<script setup>
  import { ref, computed } from 'vue'
  
  const isActive = ref(false)
  const classObj = ref({
    outer: true
  })
  const otherClass = computed(() => 'other-class')
</script>

文档里有一个示例

html 复制代码
<div :class="classObject"></div>

<script setup>
  import { ref, computed } from 'vue'
  
  const isActive = ref(true)
  const error = ref(null)
  const classObject = computed(() => ({ 
    active: isActive.value && !error.value,
    'text-danger': error.value && error.value.type === 'fatal'
  }))
</script>

这是通过计算属性的方式去绑定 class ,但是中带你不在这里,不知道大家有没有注意到 const error = ref(null) 这个 error 变量初始化赋值的是 null 。

然后在进行判断的时候 error.value && error.value.type === 'fatal' 检测 error 有值并且 error 的 type 属性值为 fatal 时渲染这个 text-danger class。

在 《JavaScript高级程序设计》 第四版这本书里讲到:null 通常作为空对象的指针来使用,如果这个变量要存储一个对象,但是现在又没有这个要存储的数据,那么就用null来填充这个变量,也就是使用null作为初始值。当然你也可以存储任何类型的值。

在组件上绑定 class

在只有一个根元素的组件中,给组件绑定 class 最终会应用到组件根元素上。

html 复制代码
<!-- 组件A A.vue -->
<div class="foo"></div>
html 复制代码
<!-- 父组件中使用 -->
<div>
  <A class="baz" />
</div>
html 复制代码
<!-- 组件A 最终生效的class -->
<div class="foo baz"></div>

什么是只有一个根元素的组件

html 复制代码
<template>
  <!-- 根元素 div -->
  <div>
    <h1>Hello</h1>
    <p>lorem</p>
  </div>
</template>

什么是多个根元素的组件

html 复制代码
<template>
  <!-- 第一个根元素 div -->
  <div></div>
  <!-- 第二个根元素 h1 -->
  <h1>Hello</h1>
  <!-- 第三个根元素 p -->
  <p>lorem</p>
</template>

绑定内联样式 也就是绑定 style

html 复制代码
<template>
   <h1 
     :style="[
       {
         color: isActive ? 'red' : '#000',
         fontSize: `${curFontSize}px`,
         ...computedStyle
       },
       otherStyle
     ]"
   >
     Hello
   </h1>
</template>

<script setup>
  import { ref, computed } from 'vue'
  
  const isActive = ref(true)
  const curFontSize = ref(20)
  const otherStyle = ref({
    padding: '8px',
    margin: '8px',
    border: '1px solid #000',
  })
  const computedStyle = computed(() => {
    if (isActive.value) {
      return {
        boxShadow: '0 0 10px 0 rgba(0,0,0,0.15)'
      }
    }
    return {}
  })
</script>
相关推荐
hunter_0764 分钟前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端
枣把儿12 分钟前
开源!公众号排版+一键发布工具懒人版
前端
2501_9160074716 分钟前
抓包工具功能对比,TraceEagle、Charles、Fiddler、Wireshark、mitmproxy 差别
前端·网络协议·ios·adb·https·fiddler·wireshark
Flynt20 分钟前
AI 写的页面一眼假?有人把"假指纹"写成 62 条规则,不用大模型就能跑
前端·ai编程·claude
kyriewen24 分钟前
我把 10 道面试题答案真跑了一遍:6 道是错的
前端·javascript·面试
WebInfra1 小时前
Rspack 2.3 发布:联手 SWC 团队带来全新编译器
前端·javascript·github
小卿噢2 小时前
同样是插 10 万行,最快的写法比最慢的快 103 倍
前端
weixin_417396832 小时前
星级酒店境外电视频道怎么合法接入?合规要点与核对清单
开发语言·前端·php·1024程序员节·综合布线
hiahiahia1232 小时前
Structured Output
前端·人工智能
FRing032 小时前
JavaScript入门到精通三十一(原型继承、原型链)
开发语言·前端·javascript