RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
vue.js中怎么绑定class和style

这篇文章将为大家详细讲解有关vue.js中怎么绑定class和style,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站建设、成都网站制作、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的秭归网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

一.绑定Class属性。

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

语法:

。class后面的双引号里接受一个对象字面量/对象引用/数组作为参数,

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

绑定对象字面量

html:


  
  状态:{{alert}}{{isSafe}}
  
//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?this.alertList[0]:this.alertList[1];
    }
  }

});

css:

.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?this.alertList[0]:this.alertList[1];
    }
  }

});

绑定数组

html:

去掉class

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


  styleBind

css

这个不需要css。。。

js

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

});

关于vue.js中怎么绑定class和style就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前文章:vue.js中怎么绑定class和style
标题链接:http://scyingshan.cn/article/goccpd.html