使用Class样式
-
数组
<h1 :class="['red','thin']">这是H1</h1> -
数组里面的三元表达式
<h1 :class="['red','thin',flag?'active':'']">这是H1</h1>
-
数组使用对象代替三元表达式,提高代码的可读性
<h1 :class="['red','thin',{'active':flag} ]">这是H1</h1> -
直接对象
在为class使用v-bind绑定对象的时候,对象的属性是类名,对象的属性可以不需要引号;属性的值是一个标识符
<h1 :class="{red:false, thin: true, italic:true, active:false}">这是H1</h1>
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./vue.js"></script>
</head>
<body>
<style>
.red{
color:red;
}
.thin{
font-weight: 100;
}
.italic{
font-style: italic
}
.active{
letter-spacing: 0.5em;
}
</style>
</body>
<div id="app">
<!--数组-->
<h1 :class="['red','thin']">这是H1</h1>
<!--三元表达式-->
<h1 :class="['red','thin',flag?'active':'']">这是H1</h1>
<!--数组使用对象代替三元表达式,提高代码的可读性-->
<h1 :class="['red','thin',{'active':flag} ]">这是H1</h1>
<!--对象-->
<h1 :class="{red:false, thin: true, italic:true, active:false}">这是H1</h1>
<!--直接指向-->
<h1 :class="classobj">这是H1</h1>
</div>
<script>
var vm = new Vue({
el: '#app',
data:{
flag : true,
classobj: {red:false, thin: true, italic:true, active:false}
},
methods:{
}
})
</script>
</html>
使用内联样式
- 直接在元素上通过
:style的形式,书写样式对象
<h1 :style="{ color:'red', 'font-weight':100 }">这是H1</h1> - 将样式对象,定义到
data中,并直接引用到:style中
<div id="app">
<!--对象就是无序键值对的集合-->
<h1 :style="styleobj">这是H1</h1>
</div>
<script>
var vm = new Vue({
el: '#app',
data:{
styleobj : { color:'red', 'font-weight':100 }
},
methods:{
}
})
</script>
- 在
:style中通过数组引用多个data上的样式对象
<div id="app">
<!--对象就是无序键值对的集合-->
<h1 :style="[styleobj,styleobj2]">这是H1</h1>
</div>
<script>
var vm = new Vue({
el: '#app',
data:{
styleobj : { color:'red', 'font-weight':100 },
styleobj2 : { 'font-style': 'italic' }
},
methods:{
}
})
</script>