【vue】class、style的用法
对象语法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<!-- <h2 :class={key1:value1,key2:value2}>{{message}}</h2>
<h2 :class={类名1:boolean,类名2:boolean}>{{message}}</h2> -->
<h2 :class={active:isActive,line:isLine}>{{message}}</h2>
<h2 class="title" :class={active:isActive,line:isLine}>{{message}}</h2>
<!-- 方法实现 -->
<h2 class="title" :class=getClasses()>{{message}}</h2>
<!-- 计算属性 -->
<h2 class="title" :class=classes>{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
isActive:true,
isLine:false
},
computed: {
classes:function(){
return {active:this.isActive,line:this.isLine}
}
},
methods: {
getClasses:function(){
return {active:this.isActive,line:this.isLine}
}
},
})
</script>
</body>
</html>
<div
class="static"
:class="{ active: isActive, 'text-danger': hasError }">
</div>
<view class="left" :class="{red: item.order_type==0,blue:item.order_type==2}">
<p :style="{'color': (checkIndex3==m.txt ? '#3d8cff':'#BBBBBB')}">{{m.txt}}</p>
<li class="slider" v-bind:style="{marginLeft: leftIndex}"></li>
data: {
leftIndex: '0.167%'
}
<div v-bind:style="styleObject"></div>
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
注意:font-size写成fontSize,否则会出错
数组语法
<div :class='["classify",current=="0" ? "active" : ""]' @click='current=0'>课程</div>
注意:数组中的classify如果不加引号的话,代表的是data中的一项,并不是类名,将classify加上双引号,变成字符串就可以变成类名
三元运算符
style三元运算符
<p :style="{'color': (checkIndex3==m.txt ? '#3d8cff':'#BBBBBB')}">{{m.txt}}</p>
<span v-bind:style="{display:isActive ? 'block':'none'}">hello</span>
:style="{left: 390 + 'px',color: brandnamesum == 16 ? 'red' : ''}"
<span :style="{display:isActive ? 'block':'none'}">hello</span>
class三元运算符
<i class="iconfont" :class="[isShow=='password'?'icon-kejian':'icon-bukejian']"></i>
<li v-for="(item, index) in nav" :key="index">
<router-link :to="{ name: item.path }" :class="[item.title==activeTitle?'active':'']">{{
item.title
}}</router-link>
</li>
字符串拼接
<div :class="'classify'+(current=='0'?' active':'')" @click='current=0'>课程</div>
注意:active前要加一个空格(必须有),字符串拼接时,两个字符串之间要有空格
设置背景图片的方式
方法一
<view class="card" :style="{backgroundImage: 'url('+cardsInfo.bg+')',backgroundRepeat:'no-repeat',backgroundSize:'100% 100%'}">
</view>
方法二
<div :style="backgroundDiv"><div>
data() {
return {
backgroundDiv: {
backgroundImage:'url(' + require('./images/xxx..jpg') + ')',
backgroundRepeat:'no-repeat',
backgroundSize:'100% 100%'
}
}