详解vue.js之绑定class和style的示例代码

网络编程 发布日期:2024/10/1 浏览次数:1

正在浏览:详解vue.js之绑定class和style的示例代码

一.绑定Class属性。

绑定数据用v-bind:命令,简写成:

语法:<div v-bind:class="{ active: isActive }"></div>。class后面的双引号里接受一个对象字面量/对象引用/数组作为参数,

这里,{active: isActive}是对象参数,active是class名,isActive是一个布尔值。下面是一个例子:

绑定对象字面量

html:

<div id="classBind">
  <span :class="{warning:isWarning,safe:isSafe}" v-on:click="toggle">
  状态:{{alert}}{{isSafe}}
  </span>
</div>
//js
var app11=new Vue({
  el:'#classBind',
  data:{
    isWarning:true,
    alertList:['红色警报','警报解除'],
    alert:''
  },
  computed:{
    isSafe:function(){
      return !this.isWarning;
    }
  },
  methods:{
    toggle:function(){
      this.isWarning=!this.isWarning;
      this.alert= this.isWarning"htmlcode">
.warning{
  color:#f24;
}
.safe{
  color:#42b983;
}

当点击状态文字时,可以切换后面的文字和颜色

//状态:警报解除true

//状态:红色警报false

绑定对象引用

这里绑定的对象可以写到Vue实例的data里面,而在class="classObj ",双引号中的class是对Vue实例中classObj对象的引用。classObj可以放在data中或者computed中,如果在computed中,则classObj所对应的函数必须返回一个对象如下:

js:

var app11=new Vue({
  el:'#classBind',
  data:{
    isWarning:true,
    alertList:['红色警报','警报解除'],
    alert:''
  },
  computed: {
    isSafe: function () {
      return !this.isWarning;
    },
    classObj:function(){
      return {
        warning: this.isWarning,
        safe:this.isSafe
      }
    }
  },
  methods:{
    toggle:function(){
      this.isWarning=!this.isWarning;
      this.alert= this.isWarning"htmlcode">
<div v-bind:class="classArray" @click="removeClass()">去掉class</div>

js

data: {
classArray:["big",'red']
}
methods:{
removeClass:function(){

  this.classArray.pop();
}
}

css:

.big{
  font-size:2rem;
}
.red{
   color:red;  
}

效果,点击去掉class,会调用removeClass函数,去掉classArray数组的最后一项,第一次,去掉'red',字体颜色由红变黑,再点,去掉'big',字体变小。

二、绑定内联style

此时此刻,我一边看着本页旁边的那个Vue api文档学,一边到这里卖,装逼的感觉真爽o(^▽^)o

html

<div id="styleBind">
  <span :style="{color:theColor,fontSize:theSize+'px'}" @click="bigger">styleBind</span>
</div>

css

这个不需要css。。。

js

var app12=new Vue({
  el:'#styleBind',
  data:{
    theColor:'red',
    theSize:14
  },
  methods:{
    bigger:function(){
      this.theSize+=2;
    }
  }

});

除了传入对象字面量以外,也可以传入对象引用和数组给V-bind:style

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?