vue通过style或者class改变样式的实例代码

2019/6/26 23:23:14

本文主要是介绍vue通过style或者class改变样式的实例代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

通过style改变样式

<div :style="{ 'min-height': size + 'px' }"></div> 
<div :style="[{ 'min-height': size + 'px' },{color:'red'}]"></div> 
<div :style="{ 'opacity': value ? 0.5 : 1 }"></div> 

通过className改变样式

?<div class="static"
   v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>

<script>
data: {
 isActive: true,
 hasError: false
}
</script>

<style>
.active{
  ...
}
.text-danger{
  ...
}
</style>

PS:下面看下Vue的一些样式(class/style)绑定

样式有两种:class、style

class

  1、对象语法

    ①传给 :class 一个对象

    比如:

<div :class="{ active : isActive}"></div>

    在这里,isActive的真值决定active这个样式是否显示

    ②传给 :class 一个对象变量

    再比如,可以直接绑定一个对象

<div :class = "duixiang" ></div>

export default{
  data(){
   return{
    duixiang :{
     active : true
    }
   }
  } 
}

    ③在②的基础上,把这个对象变量放到computed计算属性里

data: {
 isActive: true,
 error: null
},
computed: {
 classObject: function () {
  return {
   active: this.isActive && !this.error,
   'text-danger': this.error && this.error.type === 'fatal',
  }
 }
}

  2、数组语法

    传给 :class 一个数组(数组里面是变量名,然后具体变量名所指的内容写到data里)

<div :class = "[ n , i]"> </div>
export default{
 data(){
  return{
   n : ' active ',
   i : ' text-danger ',
  }
  }
}

     上面的代码在最后会宣传成为<div class = "active text-anger"></div>

style

  1、对象语法

    ①传给 :style一个对象(这个对象是个JavaScript对象)。记住!CSS属性名可以用驼峰式命名

<div :style = " { color : activeColor , fontSize : fontSize + 'px' } "></div>
//然后在data里面写明,冒号后边的这个变量的实际内容,如果是单位,像px这种就直接用字符串引着就行了
data: {
 activeColor: 'red',
 fontSize: 30
}  

    ②传给 :style一个对象变量。

<div v-bind:style="styleObject"></div>
//然后在data声明这个对象变量是指代一个怎样具体的对象
data: {
 styleObject: {
  color: 'red',
  fontSize: '13px'
 }
}

同样的,对象语法常常结合返回对象的计算属性使用。

总结

以上所述是小编给大家介绍的vue通过style或者class改变样式的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!



这篇关于vue通过style或者class改变样式的实例代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程