点击下载word文档
VUE(三)
-
Class与Style绑定
操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。可以更加的动态的去展示一个模块。
-
Class 绑定
-
对象语法
-
-
<!--test1:对象语法我们可以传给 v-bind:class 一个对象,以动态地切换 class:-->
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }" id="app1"></div>
<script>
var vm = new Vue({
el: '#app1',
data: {
isActive: true,
hasError: false
}
})
</script>
<!--当 isActive 或者 hasError 变化时,class 列表将相应地更新。例如,如果 hasError 的值为 true-->
<!--绑定的数据对象不必内联定义在模板里:-->
<div v-bind:class="classObject" id="app-2"></div>
<script>
var vm = new Vue({
el: '#app-2',
data: {
classObject: {
active: true,
'text-danger': false
}
}
})
</script>
<!--渲染的结果和上面一样。我们也可以在这里绑定一个返回对象的计算属性。这是一个常用且强大的模式:-->
<div v-bind:class="classObject" id="app-3"></div>
<script>
var vm = new Vue({
el: '#app-3',
data: {
isActive: true,
error: null
},
computed: {
classObject: function () {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
})
</script>
-
数组语法
<!--test2:数组语法我们可以把一个数组传给 v-bind:class,以应用一个 class 列表:-->
<div v-bind:class="[activeClass, errorClass]" id="app-4"></div>
<script>
var vm = new Vue({
el: '#app-4',
data: {
activeClass: 'active',
errorClass: 'text-danger'
},
computed: {
classObject: function () {
return {
active: this.isActive && !this.error,
'text-danger': this.error && this.error.type === 'fatal'
}
}
}
})
</script>
<!--如果你也想根据条件切换列表中的 class,可以用三元表达式:-->
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
-
用在组件上
<!--用在组件上记住组件是要挂载到vue实例上的还有就是组件要写在实例的下方可稍后看完组件回来再看-->
<div id="app-5">
test7:<my-component class="baz boo"></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'
})
var app7 = new Vue({
el: '#app-5',
data: {}
})
</script>
-
Style绑定
-
对象语法
-
<!--注意事项:如果css属性带- 记得用引号引起来要不然渲染失败例如background-color-->
<div v-bind:style="{ 'background-color': activeColor, fontSize: fontSize + 'px' ,width:width + 'px',height: height + 'px' }" id="app_6" ></div>
<script >
var app6=new Vue({
el:'#app_6',
data: {
activeColor: 'red',
fontSize: 30,
width:20,
height:30
}
})
</script>
<div v-bind:style="styleObject" id="demo"></div>
<script >
var app6=new Vue({
el:'#demo',
data: {
styleObject:{
color: 'red',
fontSize: '13px',
width:'20px',
height:'30px',
'background-color':'red'
}
}
})
</script>
-
数组语法
<!--其实就是数组里放对象的key-->
<div v-bind:style="[baseStyles, overridingStyles]" id="app_1"></div>
<script >
var app8=new Vue({
el:'#app_1',
data: {
baseStyles:{
color: 'red',
fontSize: '13px'
},
overridingStyles:{
width:'20px',
height:'30px',
'background-color':'red'
}
}
})
</script>