基础/类与样式绑定

标签的 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>
相关推荐
用户938515635072 小时前
从零理解 React Router v6:每一个 API 都是怎么工作的
前端·javascript·全栈
用户059540174464 小时前
Redis缓存回滚踩坑实录:一个配置失误,让我在凌晨3点丢了3000条数据
前端·css
kyriewen5 小时前
别再这样写条件渲染了——你的React组件里藏着这5种定时炸弹
前端·javascript·react.js
IT_陈寒5 小时前
Redis缓存击穿把我坑惨了,原来这样设过期时间才靠谱
前端·人工智能·后端
用户938515635076 小时前
从"坐电梯"到"前端路由"——深入理解 Hash 路由原理
前端·typescript·全栈
梦想CAD控件6 小时前
网页端CAD的图形选择、编辑与夹点操作教程
前端·javascript·node.js
妙码生花6 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十二):管理员权限检查中间件,AI 随意放行预闯大祸
前端·后端·go
月月大王的3D日记6 小时前
Three.js 入门系列(8):六种光源全解析 —— 关灯了,开光!
前端·javascript
达子6667 小时前
第26章_HarmonyOs开发图解之 设备管理
vue.js