美文网首页
Class与Style绑定

Class与Style绑定

作者: 葵自渡_ | 来源:发表于2019-05-22 22:18 被阅读0次

    class绑定

    1.class对象绑定

    先看代码:

    <style type="text/css">
         .active{color:red;}
    </style>
    

    active 这个 class 存在与否将取决于数据属性 isactive 的 truthiness

    <body>
        <div id="app">
            <div @click="handleClick" :class="{active:isactive}">
                hello world
            </div>
        </div>
        <script>
            var app = new Vue({
                el:'#app',
                data:{
                    isactive:false
                },
                methods:{
                    handleClick:function(){
                        this.isactive = !this.isactive
                    }
                }
            })
        </script>
    </body>
    

    2.class数组绑定

    先看代码:

    <div id="app">
           <div :class="[active]" @click="handleDivClick">hello world</div>
    </div>
    

    这里绑定的class是以数组的形式,在data里定义一个active变量为空。

    <script>
            var app = new Vue({
                el:'#app',
                data:{
                    active:''
                },
                methods:{
                    handleClick:function(){
                        this.active = "active"
                    }
                }
            })
        </script>
    

    点击时,把class名为active的值赋值给this.active。
    此时,效果是点击之后文字颜色变红,可是再次点击就没反应,只需要改下代码

    methods:{
            handleClick:function(){
                this.active = this.active == "active" ? "" :"active"
                }
            }
    

    style绑定

    1.style对象绑定

    先看代码:

    <body>
        <div id="app">
            <div @click="handleClick" :style="styleObj">
                hello world
            </div>
        </div>
        <script>
            var app = new Vue({
                el:'#app',
                data:{
                    styleObj:{
                        color:"#333"
                    }
                },
                methods:{
                    handleClick:function(){
                        this.styleObj.color = this.styleObj.color==="red"?"#333":"red"
                    }
                }
            })
        </script>
    </body>
    

    这里给div绑定一个style,值为styleObj。
    先在data里定义styleObj,里面放着样式内容。然后点击,切换颜色样式

    2.style数组绑定

    先看代码:
    用数组的方式绑定style时,可以放入多组对象,如下代码

    <div id="app">
            <div @click="handleClick" :style="[styleObj,{background:'#ccc'}]">
                hello world
            </div>
        </div>
    

    相关文章

      网友评论

          本文标题:Class与Style绑定

          本文链接:https://www.haomeiwen.com/subject/idypzqtx.html