首页 > 代码库 > 第七节:Class与Style绑定

第七节:Class与Style绑定

1、绑定class,v-bind:class  简写为::class

  对象方式:

<!-- 绑定一个class对象,也可以绑定data中的对象-->
<span v-bind:class="{orange:isorange,  green:isgreen}">abc</span>
<span v-bind:class="colors">def</span>
 data: {
            isorange: true,
            isgreen: false,
            colors: {
                ‘orange‘: false,
                ‘green‘: true
            }
        }

     数组方式:

<span v-bind:class="[orangecolor, big]">abc</span>
<span v-bind:class="[big,colors]">def</span>
data: {
            big: "big",
            orangecolor: "orange",
            colors: {
                ‘orange‘: false,
                ‘green‘: true
            }
        }

2、绑定style  ,  v-bind:style  简写为:  :style

    对象方式:

<span v-bind:style="{color:yellowcolor,fontSize:larger}">def</span>
<span v-bind:style="fontsizes">def</span>
data: {
            larger: "30px",
            yellowcolor: "yellow",
       fontsizes: {
        ‘fontSize‘: ‘40px‘
       }
}

  数组方式:

<span v-bind:style="[fontsizes,colorstyle]">sss</span>
 data: {
           
            fontsizes: {
                ‘fontSize‘: ‘40px‘
            },
            colorstyle: {
                ‘color‘: ‘orange‘
            }

        }

3、注意在data中写style样式的时候,CSS 属性名可以用驼峰式(camelCase)或短横分隔命名(kebab-case)。

  整体的例子如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="vue.js"></script>
    <style>
        .orange {
            color: orange
        }
        
        .green {
            color: green
        }
        
        .big {
            font-size: larger;
        }
    </style>
</head>

<body>
    <div id="app">
        <!-- 绑定一个class对象,也可以绑定data中的对象-->
        <span v-bind:class="{orange:isorange,  green:isgreen}">abc</span>
        <span v-bind:class="colors">def</span>
        <span v-bind:class="[orangecolor, big]">abc</span>
        <span v-bind:class="[big,colors]">def</span>
        <!-- 绑定一个style对象,也可以绑定data中的对象-->
        <span v-bind:style="{color:yellowcolor,fontSize:larger}">def</span>
        <span v-bind:style="fontsizes">def</span>
        <!--数组语法-->
        <span v-bind:style="[fontsizes,colorstyle]">sss</span>
    </div>
</body>
<script type="text/javascript">
    var app1 = new Vue({
        el: "#app",
        data: {
            isorange: true,
            isgreen: false,
            big: "big",
            larger: "30px",
            orangecolor: "orange",
            yellowcolor: "yellow",
            colors: {
                orange: false,
                green: true
            },
            fontsizes: {
                fontSize: 40px
            },
            colorstyle: {
                color: orange
            }

        },
        methods: {

        }
    });
</script>

</html>

 

第七节:Class与Style绑定