• Vue3类与样式绑定


    官网:https://cn.vuejs.org/guide/essentials/class-and-style.html#binding-inline-styles

    绑定 HTML class

    • 绑定对象
    const isActive = ref(true)
    const hasError = ref(false)
    
    <div
      class="static"
      :class="{ active: isActive, 'text-danger': hasError }"
    ></div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    绑定的对象并不一定需要写成内联字面量的形式,也可以直接绑定一个对象

    const classObject = reactive({
      active: true,
      'text-danger': false
    })
    <div :class="classObject"></div>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    我们也可以绑定一个返回对象的计算属性

    const isActive = ref(true)
    const error = ref(null)
    
    const classObject = computed(() => ({
      active: isActive.value && !error.value,
      'text-danger': error.value && error.value.type === 'fatal'
    }))
    
    <div :class="classObject"></div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 绑定数组
    <div :class="[isActive ? activeClass : '', errorClass]"></div>
    
    <div :class="[{ active: isActive }, errorClass]"></div>
    
    • 1
    • 2
    • 3
    • 在组件上使用
      如果你的组件有多个根元素,你将需要指定哪个根元素来接收这个 class。你可以通过组件的 $attrs 属性来实现指定:
    <!-- MyComponent 模板使用 $attrs 时 -->
    <p :class="$attrs.class">Hi!</p>
    <span>This is a child component</span>
    
    <MyComponent class="baz" />
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这将被渲染为:

    <p class="baz">Hi!p>
    <span>This is a child componentspan>
    
    • 1
    • 2

    绑定内联样式(style)

    • 绑定对象
      直接绑定一个样式对象通常是一个好主意,这样可以使模板更加简洁,如果样式对象需要更复杂的逻辑,也可以使用返回样式对象的计算属性
    const styleObject = reactive({
      color: 'red',
      fontSize: '13px'
    })
    
    <div :style="styleObject"></div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 绑定数组
    <div :style="[baseStyles, overridingStyles]">div>
    
    • 1

    自动前缀

    当你在 :style 中使用了需要浏览器特殊前缀的 CSS 属性时,Vue 会自动为他们加上相应的前缀。Vue 是在运行时检查该属性是否支持在当前浏览器中使用。如果浏览器不支持某个属性,那么将尝试加上各个浏览器特殊前缀,以找到哪一个是被支持的。

    样式多值

    你可以对一个样式属性提供多个 (不同前缀的) 值,举例来说:

    <div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }">div>
    
    • 1

    数组仅会渲染浏览器支持的最后一个值。在这个示例中,在支持不需要特别前缀的浏览器中都会渲染为 display: flex

  • 相关阅读:
    ASCII码转HEX与HEX转ASCII码
    SpringBoot进阶-第三方bean属性绑定
    RabbitMQ真实生产故障问题还原与分析
    HTML超链接标签
    全球化系统设计:多时区处理
    微调Qwen2大语言模型加入领域知识
    JAVA中的集合类型的理解及应用
    Blazor和Vue对比学习(基础1.3):属性和父子传值
    python之判断是否是目录或文件
    JSP中page指令的import命令具有什么功能呢?
  • 原文地址:https://blog.csdn.net/weixin_43960767/article/details/128041999