绑定样式

suaxi
2022-05-26 / 0 评论 / 24 阅读 / 正在检测是否收录...

1. class样式

语法::class="xxx",xxx可以是字符串、对象、数组

字符串适用于:类名不确定,要动态获取;

对象使用于:要绑定的样式个数、名字不确定;

数组适用于:要绑定的样式个数、名字确定,但需要动态决定是否使用;

2. style样式

语法::style="{fontSize: xx + 'px'}",xxx为动态值

:style:="[a,b]",ab为数组形式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绑定样式</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    <style>
        .basic{
            width: 400px;
            height: 100px;
            border: 1px solid black;
        }

        .happy{
            border: 4px solid red;;
            background-color: rgba(255, 255, 0, 0.644);
            background: linear-gradient(30deg,yellow,pink,orange,yellow);
        }
        .sad{
            border: 4px dashed rgb(2, 197, 2);
            background-color: gray;
        }
        .normal{
            background-color: skyblue;
        }

        .test1{
            background-color: yellowgreen;
        }
        .test2{
            font-size: 30px;
            text-shadow:2px 2px 10px red;
        }
        .test3{
            border-radius: 20px;
        }
    </style>
</head>
<body>
<div id="root">
    <h2>你好,{{name}}</h2>
    <!-- 绑定class,字符串写法,适用于样式的类名不确定,需要动态的指定 -->
    <div class="basic" :class="mood" @click="changeMood">
        {{name}}
    </div>
    <br>

    <!-- 绑定class,数组写法,适用于要绑定的样式个数、名字不确定 -->
    <div class="basic" :class="classArr">{{name}}</div>
    <br>

    <!-- 绑定class,数组写法,适用于要绑定的样式个数、名字确定,但动态决定用不用 -->
    <div class="basic" :class="classObj">{{name}}</div>
    <br>

    <div class="basic" :style="styleObj">{{name}}</div>
    <br>
</div>

<script type="text/javascript">
    //关闭开发环境提示
    Vue.config.productionTip = false

    //创建Vue实例
    new Vue({
        el: '#root',
        data: {
            name: '孙笑川',
            mood: 'normal',
            classArr: ['test1','test2','test3'],
            classObj: {
                test1: true,
                test2: false,
                test3: true,
            },
            styleObj: {
                fontSize: '40px'
            }
        },
        methods: {
            changeMood() {
                const arr = ['happy','sad','normal'];
                const index = Math.floor(Math.random() * 3);
                this.mood = arr[index];
            }
        }
    })
</script>
</body>
</html>
0

评论 (0)

取消