class绑定
(1) 直接绑定下面的style里面的样式
template里面的
<h1 class='h1'>hello</h1>
style里面的
.h1{
color:red
}
对象写法
(1) 用到script里面的数据 根据数据进行判断使用类
template:
<h1 :class='{ h1:isShow }'>hello</h1> //当isShow为false时不会显示 为true时显示
script:
data(){
return{
isShow:false
}
}
style:
.h1{ color:red }
(2)也可以绑定多个数据进行判断
<h1 class='{ h1:isShow,h2:isActive' }></h1>
scipt:
data(){
return{
isShow:false,
isActive:true
}
}
它等同于class='h2'
绑定一个数据中的对象
<h1 :class='myClass'>hello</h1>
data:
myClass:{
h1:true,
h2:false
}
上面的可以渲染为class='h1'
绑定一个计算属性
<div v-bind:class="classObject"></div>
data: {
isActive: true,
error: null
},
computed: {
classObject: function () {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
上面的可以渲染为class='active'
三元运算符
<h1 :class="isShow ? 'h1' : 'h2'">hello</h1>
数组形式
(1) 使用多个类时 可以使用数组
<h1 :class='[showClass,activeClass]'>hello</h1>'
data:
showClass:'h1',
activeClass:'h2'
上面可以渲染为 class='h1 h2'
(2) 数组中三元运算符
<h1 :class="[isShow ? 'h1' : '' , 'h3' ]">hello</h1>
前面的是使用h1 还是空 是根据isShow这个数据进行判断 但是h3都存在
上面的写的复杂 所以可以使用数组里面包含对象
(3)数组里面也可以使用对象
<h1 class='[{h1:isShow},h2]'>hello</h1>'
组件中的
当在一个自定义组件上使用 class 属性时,这些 class 将被添加到该组件的根元素上面。这个元素上已经存在的 class 不会被覆盖。
声明组件
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
然后在使用它的时候添加一些 class:
<my-component class="baz boo"></my-component>
HTML 将被渲染为:
<p class="foo bar baz boo">Hi</p>
对于带数据绑定 class 也同样适用:
<my-component v-bind:class="{ active: isActive }"></my-component>
当 isActive 为 truthy[1] 时,HTML 将被渲染成为:
<p class="foo bar active">Hi</p>
style
对象
数据是一个值
<h1 :style='{color:myColor,fontSize:fontSize+"px"}'>hello</h1>
data:
myColor:'red',
fontSize:30
绑定数据是一个对象
<h1 :style='myStyle'>hello</h1>
data:
myStyle:{
color:'red',
border:1px soild red,
fontSize:30px
}
数组
数组语法可以将多个样式对象应用到同一个元素上
<h1 :style='[baseStyles,myStyle]'>hello</h1>