解读mpvue官方文档的Class 与 Style 绑定及不支持语法

在vue.js项目转化为小程序时,把原来页面的代码直接拷贝过去,发现布局改变很多,很多已经设置的标签的css样式并没有显示出来,查看官方文档,得知原来vue.js的Class 与 Style 绑定语法,有些不适合mpvue,以下总结几点:

一. :class绑定方式
(1).mpvue支持:class="{ active: isActive }"

<template>
  <div>
      <div :class="{career:true}">测试</div>
  </div>
</template>

.career{
 background: red;
}

(2).mpvue支持三元表达式(v-bind:class="[isActive ? activeClass : ’ '])

<template>
 <div>
     <div :class="[isTest?'career':'']">测试</div>
 </div>
</template>
data () {
   return {
       isTest:ture
      } 
  }

(3).mpvue支持动态数组(:class="[{‘career’: isTest} , ‘bottom’]")

<template>
  <div>
      <div :class="[{'career': isTest} , 'bottom']">测试</div>
  </div>
</template>
data () {
    return {
        isTest:ture
       } 
   }
.career{
 background: red;
}
. bottom{
   background: yellow;  
}

(4).mpvue不支绑定对象的形式(:class=“ClassObject”)

<template>
  <div>
      <div :class="career">测试</div>
  </div>
</template>

.career{
 background: red;
}

这种绑定对象的方式在vue.js上可以,在mpVue上不可行。根据官方提示我们可以用 computed 方法生成 class 或者 style 字符串,插入到页面中。

更改为适合mpvue 的形式代码:

<template>
  <div>
      <div :class="computedClassObject">测试</div>
  </div>
</template>

computed: {
        computedClassObject () {
            return 'career'//重点:只需要在computed 方法生成 class的字符串
        }
    },

<style>
.career{
 background: red;
}
</style>

二. :style绑定方式

(1). mpvue支持直接在模板中使用:style

<template>
  <div>
      <div :style="{background: 'red'}">测试</div>
  </div>
</template>

(2).mpvue支持多组绑定(驼峰写法)

<template>
  <div>
      <div :style="{'background':'bgColor',fontSize: fontSize + 'px'}">测试</div>
  </div>
</template>
data(){
      return {
       bgColor: 'red',
        fontSize: 18,
      }
    }

(3).mpvue不支持绑定对象

<template>
  <div>
      <div :style="styleObj">测试</div>
  </div>
</template>

data () {
    return {
        styleObj: {
            type: Object,
            default: function () {
                return {
                    background: 'black',
                    color: "yellow"
                }
            }
        }
    }
  },

这种直接绑定对象的方式在mpvue上也是不可行的,需要做一下的修改。
根据官方文档提示作如下支持mpvue的修改为:

<template>
  <div>
      <div :style="computedClassObject">测试</div>
  </div>
</template>

computed: {
        computedClassObject () {
            return this.showJson({
                background: 'red',
                color:"yellow"
            })
        }
    }

把对象格式的style转化为字符串格式方法:

将对象转变为style字符串
showJson(style){
          for(let i in style){
              s.push(i+':'+style[i]);
          }
          s = s.join(';')
          return  s
      }

总结:根据官方指出最佳实践最好选择mpvue支持的语法,从性能考虑,建议不要过度依赖此。最后官方指出暂不支持在组件上使用 Class 与 Style 绑定。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值