vue的样式绑定

97 阅读2分钟

“Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。”

vue的样式绑定其实无非就是class和style两种,翻翻文档其实也就知道怎么写了。但是我每次用到的时候都去翻文档,对于各种使用和写法也不太熟悉,故在此写下这篇文章,帮助自己熟悉写法,开发时能快速写出,而不用老是去翻文档o( ̄┰ ̄*)ゞ

class

对象写法

键——值

<div :class="{classObj1: true,  classObj2: active}"></div>

...
data() {
    return {
    // 通过控制active,来决定是否添加classObj2
        active: false
    }
}
...

数组写法

// (1)
<div :class="['classObj1', active ? classObj2:'']"></div>
// (2)数组写法内可以包含对象写法
<div :class="['classObj1', {classObj2: active}]"></div>

...
data() {
    return {
    // 通过控制active,来决定是否添加classObj2
        active: false
    }
}
...

style

// 不需要动态写时
<div style="{fontSize: 14px; backgroundColor: red;}"></div>

style的属性名可以用驼峰式fontSize或短横线font-size写法。

对象写法

<div :style="{color: myColor,  fontSize: myFontSize}"></div>
...
data() {
    return {
        myColor: red,
        myFontSize: '14px'
    }
}
...

直接绑定一个data里面的style对象

<div :style="styleObj"></div>
...
data() {
    return {
        styleObj: {
            myColor: red,
            myFontSize: '14px'
        }
    }
}
...

直接绑定一个style对象与直接绑定一个class有什么区别:

绑定一个style对象,在vue的script中可以直接操作data里面的style对象,而对于绑定class,需要在css中定义class,且里面的style样式是固定的,不能在script里直接操作。

数组写法

<div :style="[styleObj1, styleObj2]"></div>
···
data() {
    return {
        styleObj1: {color: red, fontSize: '14px'}
        styleObj2: {overflow: 'hidden', lineHeight: '24px'}
    }
}
···

一些场景

一、假设你有一个button的功能组件,button的样式是不确定,点击功能是一样的

// myBtn组件,myBtn.vue
<button @click="clickBtn" :style="btnStyle"></button>
...
props: {
    width: {
        type: String,
        default: '200px'
    },
    height: {
        type: String, 
        default: '100px'
    },
    fontSize: {
        type: String,
        default: '14px'
    }
}
methods: {
    clickBtn() {
    // 点击按钮,实现功能
    }
},
computed: {
    btnStyle() {
        return {
            fontSize: this.fontSize,
            height: this.height,
            width: this.width
        }
    }
}
...

上述是将props中button的样式组合写在了computed中,其实也可以组合写在data中,像上述style的对象写法一样。

二、组件内定义了两个样式,根据传入的props决定使用哪一个样式

// 之前好傻的写法╮(╯▽╰)╭
<div :class="{theme ===  'light' ? 'light': 'dark'}">
</div>

// 直接使用数组,将传入的prop写进去就可以了
<div :class="[theme]"></div>
...
props: {
    theme: {
        type: String,
        default: 'light'
    }
}
...
<style scoped>
.dark {...}
.light {...}
</style>