Vue3 样式动态绑定

Vue.js class
class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。

v-bind 在处理 class 和 style 时, 表达式除了可以使用字符串之外,还可以是对象或数组。

v-bind:class 可以简写为 :class。

class 属性绑定
我们可以为 v-bind:class 设置一个对象,从而动态的切换 class:

一、class 属性绑定

我们可以为 v-bind:class 设置一个对象,从而动态的切换 class:

1.1 、实例 1

实例中将 isActive 设置为 true 显示了一个绿色的 div 块,如果设置为 false 则不显示:

<div :class="{ 'active': isActive }"></div>

以上实例 div class 渲染结果为:

<div class="active"></div>

案例: 

 

 <div class="switch-panel" id="switch-panel">
          <div :class="{ active: isSwitchTable }" @click="switchPanel(true)">
            <svg-icon icon-class="biz_table" style="width: 20px; height: 20px; cursor: pointer" />
          </div>
          <div :class="{ active: !isSwitchTable }" @click="switchPanel(false)">
            <svg-icon icon-class="biz_list" style="width: 20px; height: 20px; cursor: pointer" />
          </div>
        </div>


// 切换table(表格)或者 panel(看板)
function switchPanel(value) {
  isSwitchTable.value = value
  localStorage.setItem("bizIsSwitchTable", JSON.stringify(isSwitchTable.value))
}


  .switch-panel {
      display: flex;
      margin-right: 30px;
      > div {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 42px;
        height: 32px;
        background: #ffffff;
        border: 1px solid #dcdee0;
        border-left: none;
        color: #939ba6;
      }
      > div:first-child {
        border-left: 1px solid #dcdee0;
        border-radius: 2px 0 0 2px;
      }
      > div:last-child {
        border-radius: 0 2px 2px 0;
      }
      div.active {
        border-color: #477fff;
        color: #477fff;
        &:not(:first-child) {
          box-shadow: -1px 0 0 0 #477fff;
        }
      }
    }

1.2实例 2

text-danger 类背景颜色覆盖了 active 类的背景色:

<div class="static" :class="{ 'active' : isActive, 'text-danger' : hasError }">
</div>

以上实例 div class 渲染结果为:

<div class="static text-danger"></div>

当 isActive 或者 hasError 变化时,class 属性值也将相应地更新。例如,如果 active 的值为 true,class 列表将变为 "static active text-danger"。

我们也可以直接绑定数据里的一个对象:

1.3实例 3

text-danger 类背景颜色覆盖了 active 类的背景色:

<div id="app">
    <div class="static" :class="classObject"></div>
</div>

实例 3 与 实例 2 的渲染结果是一样的。

此外,我们也可以在这里绑定一个返回对象的计算属性。这是一个常用且强大的模式:

1.4、实例 4

data() {
  return {
    isActive: true,
    error: null
  }
},
computed: {
  classObject() {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}
数组语法

我们可以把一个数组传给 v-bind:class ,实例如下:

1.5、实例 5

<div class="static" :class="[activeClass, errorClass]"></div>

 以上实例 div class 渲染结果为:

<div class="static active text-danger"></div>

我们还可以使用三元表达式来切换列表中的 class :

1.6、实例 6

errorClass 是始终存在的,isActive 为 true 时添加 activeClass 类:

<div id="app">
    <div class="static" :class="[isActive ? activeClass : '', errorClass]"></div>
</div>

以上实例 div class 渲染结果为:

<div class="static text-danger"></div>

1.7 实例7

<div :class="['customer_content', { customer_content_panel: !isSwitchTable }]"/>

二 、Vue.js style(内联样式)

我们可以在 v-bind:style 直接设置样式,可以简写为 :style:

2.1、实例 1

<div id="app">
    <div :style="{ color: activeColor, fontSize: fontSize + 'px' }">菜鸟教程</div>
</div>

以上实例 div style 渲染结果为:

<div style="color: red; font-size: 30px;">菜鸟教程</div>

也可以直接绑定到一个样式对象,让模板更清晰:

案例

 <el-icon
      color="#606060"
      class="addTag"
      @click="addTag"
      :style="tags?.length ? 'margin-top: -12px;' : ''"
      v-if="props.isDddTag"
    >
      <CirclePlusFilled />
    </el-icon>

案例

<svg-icon
            @mouseover.stop
            @mouseout.stop
            :icon-class="formatPayState(item.state).icon"
            :style="`width: ${formatPayState(item.state)?.width || '15px'}; height: ${formatPayState(item.state)?.height || '15px'};color: #fff`"
          />

const formatPayState = (state) => {
  return bizStateMap[state]
}


export const bizStateMap = {
  1: {
    name: "新商机",
    icon: "biz_new",
    color: "#FF7600",
    width: "20px",
    height: "20px"
  },
}

案例

  <div class="zq-top-authorize_itemText">
                            <span :style="{
                                'background-color':
                                    item?.oauthState === '已授权'
                                        ? '#00B700'
                                        : '#FF0000',
                            }"></span>
                            <i>{{ item?.oauthState }}</i>
                        </div>

2.2、实例 2

<div id="app">
  <div :style="styleObject">菜鸟教程</div>
</div>

v-bind:style 可以使用数组将多个样式对象应用到一个元素上:

2.3、实例 3

<div id="app">
  <div :style="[baseStyles, overridingStyles]">菜鸟教程</div>
</div>

注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。

多重值

可以为 style 绑定中的 property 提供一个包含多个值的数组,常用于提供多个带前缀的值,例如:

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

 这样写只会渲染数组中最后一个被浏览器支持的值。在本例中,如果浏览器支持不带浏览器前缀的 flexbox,那么就只会渲染 display: flex。

三 、组件上使用 class 属性

当你在带有单个根元素的自定义组件上使用 class 属性时,这些 class 将被添加到该元素中。此元素上的现有 class 将不会被覆盖。

3.1 、实例 1

<div id="app">
    <runoob class="classC classD"></runoob>
</div>
 
<script>
// 创建一个Vue 应用
const app = Vue.createApp({})
 
// 定义一个名为 runoob的新全局组件
app.component('runoob', {
    template: '<h1 class="classA classB">I like runoob!</h1>'
})
 
app.mount('#app')
</script>

以上实例 div class 渲染结果为:

<h1 class="classA classB classC classD">I like runoob!</h1>

对于带数据绑定 class 也同样适用:

<my-component :class="{ active: isActive }"></my-component>


当 isActive 为 true 时,HTML 将被渲染成为:

<p class="active">Hi</p>

如果你的组件有多个根元素,你需要定义哪些部分将接收这个类。可以使用 $attrs 组件属性执行此操作:

3.2 、实例 2

<div id="app">
    <runoob class="classA"></runoob>
</div>
 
<script>
const app = Vue.createApp({})
 
app.component('runoob', {
  template: `
    <p :class="$attrs.class">I like runoob!</p>
    <span>这是一个子组件</span>
  `
})
 
app.mount('#app')
</script>

注意:template 中 ` 是反引号,不是单引号 '。

以上实例 div class 渲染结果为:

<div id="app" data-v-app=""><p class="classA">I like runoob!</p><span>这是一个子组件</span></div>

  • 18
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值