基础/类与样式绑定

标签的 classstyle 也属于 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 有值并且 errortype 属性值为 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>
相关推荐
盛夏绽放9 分钟前
接口验证机制在Token认证中的关键作用与优化实践
前端·node.js·有问必答
zhangxingchao25 分钟前
Jetpack Compose 之 Modifier(中)
前端
JarvanMo25 分钟前
理解 Flutter 中 GoRouter 的context.push与context.go
前端
pe7er31 分钟前
使用 Vue 官方脚手架创建项目时遇到 Node 18 报错问题的排查与解决
前端·javascript·vue.js
星始流年35 分钟前
前端视角下认识AI Agent
前端·agent·ai编程
pe7er38 分钟前
使用 types / typings 实现全局 TypeScript 类型定义,无需 import/export
前端·javascript·vue.js
CH_Qing39 分钟前
【udev】关于/dev 设备节点的生成 &udev
linux·前端·网络
小诸葛的博客44 分钟前
gin如何返回html
前端·html·gin
islandzzzz1 小时前
(第二篇)HMTL+CSS+JS-新手小白循序渐进案例入门
前端·javascript·css·html
喝拿铁写前端1 小时前
前端实战优化:在中后台系统中用语义化映射替代 if-else,告别魔法数字的心智负担
前端·javascript·架构