这里有新鲜出炉的 vue.js 教程,程序狗速度看过来!
Vue.js 是构建 web 界面的 JavaScript 库,提供数据驱动的组件,还有简单灵活的 API,使得 MVVM 更简单。
数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。这篇文章主要介绍了 vue.js 绑定 style 和 class 的相关资料, 需要的朋友可以参考下
数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是 attribute,我们可以用 v-bind 处理它们:只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在 v-bind 用于 class 和 style 时,Vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。
一. 绑定 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?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
以上所述是小编给大家介绍的 vue.js 学习笔记之绑定 style 和 class,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 phperz 网站的支持!
来源: http://www.phperz.com/article/17/0511/330782.html