当前位置:主页 > 网页前端 > vue >

详解mpvue scroll-view自动回弹bug解决方案

时间:2021-01-13 09:59:14 | 栏目:vue | 点击:

表现

设置了scroll-top的scroll-view组件,在组件所在vue实例data发生改变时会自动回弹到最上方

解决方案

打开 node_modules/mpvue/index.js, 在任意位置添加以下两个方法

function calcDiff(holder, key, newObj, oldObj) {
 if (newObj === oldObj || newObj === undefined) {
  return
 }

 if (newObj == null || oldObj == null || typeof newObj !== typeof oldObj) {
  holder[key] = newObj
 } else if (Array.isArray(newObj) && Array.isArray(oldObj)) {
  if (newObj.length === oldObj.length) {
   for (var i = 0, len = newObj.length; i < len; ++i) {
    calcDiff(holder, key + '[' + i + ']', newObj[i], oldObj[i])
   }
  } else {
   holder[key] = newObj
  }
 } else if (typeof newObj === 'object' && typeof oldObj === 'object') {
  var newKeys = Object.keys(newObj)
  var oldKeys = Object.keys(oldObj)

  if (newKeys.length !== oldKeys.length) {
   holder[key] = newObj
  } else {
   var allKeysSet = Object.create(null)
   for (var i = 0, len = newKeys.length; i < len; ++i) {
    allKeysSet[newKeys[i]] = true
    allKeysSet[oldKeys[i]] = true
   }
   if (Object.keys(allKeysSet).length !== newKeys.length) {
    holder[key] = newObj
   } else {
    for (var i = 0, len = newKeys.length; i < len; ++i) {
     var k = newKeys[i]
     calcDiff(holder, key + '.' + k, newObj[k], oldObj[k])
    }
   }
  }
 } else if (newObj !== oldObj) {
  holder[key] = newObj
 }
}

function diff(newObj, oldObj) {
 var keys = Object.keys(newObj)
 var diffResult = {}
 for (var i = 0, len = keys.length; i < len; ++i) {
  var k = keys[i]
  var oldKeyPath = k.split('.')
  var oldValue = oldObj[oldKeyPath[0]]
  for (var j = 1, jlen = oldKeyPath.length; j < jlen && oldValue !== undefined; ++j) {
   oldValue = oldValue[oldKeyPath[j]]
  }
  calcDiff(diffResult, k, newObj[k], oldValue)
 }
 return diffResult
} 

2.找到 throttleSetData 修改为

var throttleSetData = throttle(function (page, data) {
 page.setData(diff(data, page.data));
}, 50); 

3.找到 updateDataToMP 方法, 将 throttleSetData 的调用方式改为

throttleSetData(page, data);

希望官方早日修复,参考:

使用脏检查优化每次更新数据时都会传输大量数据的问题, 解决删除回退, 列表忽然滚动到顶部等问题

您可能感兴趣的文章:

相关文章