首页 > php教程 > PHP开发 > 正文

vue.js之绑定style样式和class列表

高洛峰
发布: 2016-12-08 13:49:23
原创
1721人浏览过

数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是 attribute,我们可以用 v-bind 处理它们:只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在 v-bind 用于 class 和 style 时,vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。

一.绑定Class属性。

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

语法:

。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?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:

<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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号