vue绑定class样式

vue绑定class样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style >
        *{
            margin-top: 20px;
        }
        .basic{
            border:  1px solid ;
        }
        .happy{
            border: 4px solid  red;
            background-color: rgba(red, green, blue, alpha);
            background: linear-gradient(30deg,yellow,pink,orange,yellow);
        }
        .sad{
            border: 4px solid  rgb(0, 68, 255);
            background-color: rgba(red, green, blue, alpha);
            background: linear-gradient(30deg,yellow,pink,orange,yellow);
        }
    </style>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<body>
    <div id="root">
        <!-- 绑定class样式 字符串写法 适用于:样式的类名不确定,需要动态指定 -->
        <div  class="basic" :class="a" >
        {{name}}
    </div>
<br>
<!-- 绑定class样式:数组写法,适用于:要绑定的样式个数不确定,名字也不确定 -->
    <div class="basic " :class="classarr">
        {{name}}
    </div>
<!-- 绑定class的对象写法,适用于: 要绑定的样式个数确定,名字也确定,但要动态决定用不用-->
    <div class="basic" :class="classobj">
        {{name}}
    </div>

    <br>
        <div>
            <button @click="changemood">click me</button>
        </div>
    </div>
    
</body>
<script>
  const v=  new Vue({
        el:'#root',
        data: {
            name:'hello',
            a:'sad',
            classarr:['happy','sad'],
            classobj:{
                happy:false,
                sad:false
            }
        },
        methods: {
            changemood(){
                const arr=['happy','sad']
               const index= Math.floor(Math.random()*2);
                this.a=arr[index];
               
            }
        },
    })
</script>
</html>
posted @ 2021-11-16 18:20  ABkjlhkj  阅读(47)  评论(0)    收藏  举报