vue中class和style设置的相关方法

高洛峰
高洛峰 原创
2017-02-18 14:50:06 1130浏览

class&style样式设置

class

html代码

<p id="box">
    <strong>阿斯顿发</strong>
</p>

css代码

.red {
    color: red;
}
.gray {
    background-color: gray;
}

js代码

window.onload = function() {
    new Vue({
        el: '#box',
        data: {
            red: 'red',
            gray: 'gray'
        }
    });
}

样式生效的写法

  1. :class="[red, gray]" 调用的是vue参数里的data属性

    <strong :class="[red, gray]"></strong>
  2. :class="{red: true, gray: true}"

    <strong :class="{red: true, gray: true}"></strong>

    第二种方法也是可以调用vue参数了的data属性的,记住,Vue里面一切皆是数据

    new Vue({
        el: '#box',
        data: {
           red: 'red',
           gray: 'gray',
           a: true,
           b: false
     }   
    });
    <strong :class="{red: a, gray: b}"></strong>
  3. :class="json",第二种方法的精简版,官方版本

    new Vue({
        el: '#box',
        data: {
            red: 'red',
            gray: 'gray',
            json: {
                a: true,
                b: false
            }
        }
    });
<strong :class="json"></strong>

style

和class基本相同

  1. :style="{}"

<strong :style="{color: 'red', backgroundColor: 'gray'}"></strong>
  1. :style="a"

    new Vue({
        el: '#box',
        data: {
            red: 'red',
            gray: 'gray',
            a: {
                color: 'red',
                backgroundColor: 'gray' //注意复合样式的书写规范
            }
        }
    });
    <strong :style="a">阿斯顿发</strong>
  2. :style="[a, b]", a, b对应的是data里的两个json数据

更多vue中class和style设置的相关方法 相关文章请关注PHP中文网!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:CSS3 文本换行 下一条:CSS结构与布局