** 初序 **
纸上得来终觉浅,绝知此事要躬行
在上一章关于《Vue重学Day01》中已经讲了Vue的基本指令,接着补充几点
v-bind:class 绑定类样式
class和style是HTML元素的属性,用于设置元素的样式。v-bind在处理bind和style时,表达式的结果类型除了字符串之外,还可以是对象或数组。
动态切换多个class
<style>
.active{
width:100px;
height:100px;
background:green;
}
.text-danger{
background:red;
}
</style>
<body>
<div id="app">
<div class="static" :class="{'active':isActive,'text-danger':hasError}">
</div>
</div>
<script src="./vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
isActive: true,
hasError: true
return {
isActive,
hasError
}
}
})
</script>
</body>
将样式绑定对象
<body>
<div id="app">
<div :class="classObject"></div>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
classObject: {
active: true,
'text-danger': true
}
return{
calssObject
}
}
})
</script>
效果上两者皆是一样
computed对象属性
<body>
<div id="app">
<div :class="classObject"></div>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
cisActive: true,
error: null
return{
}
},
computed:{
classObject(){
return{
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
})
</script>
数组语法
<style>
.active {
width: 100px;
height: 100px;
background: green;
}
.text-danger {
background: red;
}
</style>
<body>
<div id="app">
<div :class="[activeClass,errorClass]"></div>
</div>
</body>
<script>
const app = new Vue({
el:'#app',
data: {
activeClass: 'active',
errorClass: 'text-danger
return{
activeClass,
errorClass
}
}
})
</script>
效果显示为红色
三元表达式
<style>
.active {
width: 100px;
height: 100px;
background: green;
}
.text-danger {
background: red;
}
</style>
<body>
<div id="app">
<div :class="[errorClass ,isActive ? activeClass : '']"
></div>
</div>
<script>
const app = new Vue({
el:'#app',
data: {
isActive:true,
activeClass: 'active',
errorClass: 'text-danger'
}
})
</script>
</body>
v-bind:style 动态绑定样式
直接添加样式属性
<body>
<div id="app">
<div :style="{ color: activeColor, fontSize: fontSize + 'px',background:'red' }">内联样式</div>
></div>
</div>
<script>
const app = new Vue({
el:'#app',
data: {
activeColor: 'green',
fontSize: 30
}
})
</script>
</body>
绑定到样式对象
<body>
<div id="app">
<div :style="styleObject">绑定样式对象</div>
</div>
</div>
<script>
const app = new Vue({
el:'#app',
data: {
styleObject: {
color: 'green',
fontSize: '30px',
background:'red'
}
}
})
</script>
</body>
多样式绑定
<body>
<div id="app">
<div :style="[baseStyles, overridingStyles]">绑定样式对象</div>
</div>
</div>
<script>
const app = new Vue({
el:'#app',
data: {
baseStyles: {
color: 'green',
fontSize: '30px',
background:'red'
},
overridingStyles: {
'font-weight': 'bold'
}
}
})
</script>
</body>
当:style使用需要特定前缀的CSS属性时,如transiform,Vue.js会自动侦测并添加相应的前缀