在mpvue项目中,由于:class和:style样式不能是对象的形式,必须转化为字符串,就需要下面的转化方法。
一.json对象转字符串

 showJson(style){
          for(let i in style){
              s.push(i+':'+style[i]);
          }
          s = s.join(';')
          console.log(s)
          return  s
      }

使用方法:

computedClassObject () {
            return this.showJson({
                background: 'red',
                color:"yellow",
                'font-size':'16px'
            })
        }

二.json对象转字符串

// 样式转对象
function styleToObj(style) {
if (!style || style == '') { return }
var Arr = style.split(';')
Arr = Arr.filter(item => {
return item != ''
})
let str = ''
Arr.forEach(item => {
let test = ''
trim(item).split(':').forEach(item2 => {
test += '"' + trim(item2) + '":'
})
str += test + ','
})
str = str.replace(/:,/g, ',')
str = str.substring(0, str.lastIndexOf(','))
str = '{' + str + '}'
return JSON.parse(str)
}


/**
* 去掉字符串前后所有空格
*/
function trim (str, isglobal) {
var result
result = str.replace(/(^\s+)|(\s+$)/g, '')
if (isglobal && isglobal.toLowerCase() === 'g') {
result = result.replace(/\s/g, '')
}
return result
}
Logo

前往低代码交流专区

更多推荐