setData.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import _set from '../utils/_set'
  2. import debounce from '../utils/debounce'
  3. /**
  4. * 老setData polyfill
  5. * 用于转换后的uniapp的项目能直接使用this.setData()函数
  6. * @param {*} obj
  7. * @param {*} callback
  8. */
  9. function oldSetData (obj, callback) {
  10. let that = this
  11. const handleData = (tepData, tepKey, afterKey) => {
  12. var tepData2 = tepData
  13. tepKey = tepKey.split('.')
  14. tepKey.forEach(item => {
  15. if (tepData[item] === null || tepData[item] === undefined) {
  16. let reg = /^[0-9]+$/
  17. tepData[item] = reg.test(afterKey) ? [] : {}
  18. tepData2 = tepData[item]
  19. } else {
  20. tepData2 = tepData[item]
  21. }
  22. })
  23. return tepData2
  24. }
  25. const isFn = function (value) {
  26. return typeof value == 'function' || false
  27. }
  28. Object.keys(obj).forEach(function (key) {
  29. let val = obj[key]
  30. key = key.replace(/\]/g, '').replace(/\[/g, '.')
  31. let front, after
  32. let index_after = key.lastIndexOf('.')
  33. if (index_after != -1) {
  34. after = key.slice(index_after + 1)
  35. front = handleData(that, key.slice(0, index_after), after)
  36. } else {
  37. after = key
  38. front = that
  39. }
  40. if (front.$data && front.$data[after] === undefined) {
  41. Object.defineProperty(front, after, {
  42. get () {
  43. return front.$data[after]
  44. },
  45. set (newValue) {
  46. front.$data[after] = newValue
  47. that.hasOwnProperty("$forceUpdate") && that.$forceUpdate()
  48. },
  49. enumerable: true,
  50. configurable: true
  51. })
  52. front[after] = val
  53. } else {
  54. that.$set(front, after, val)
  55. }
  56. })
  57. // this.$forceUpdate();
  58. isFn(callback) && this.$nextTick(callback)
  59. }
  60. /**
  61. * 变量名正则
  62. */
  63. const variableNameReg = /^([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*$/
  64. /**
  65. * 2022-10-31 重写setData
  66. * 2023-05-08 增加微信“简易双向绑定”支持
  67. * 用于转换后的uniapp的项目能直接使用this.setData()函数
  68. * @param {Object} obj
  69. * @param {Object} callback
  70. */
  71. export function setData (obj, callback = null) {
  72. Object.keys(obj).forEach((key) => {
  73. _set(this, key, obj[key])
  74. //处理微信“简易双向绑定”
  75. if (variableNameReg.test(key) && key.endsWith("Clone")) {
  76. let propName = key.replace(/Clone$/, "")
  77. if (this.$options && this.$options.propsData[propName]) {
  78. this.$emit(`update:${propName}`, obj[key])
  79. }
  80. }
  81. })
  82. this.$forceUpdate();
  83. if (typeof callback == 'function') this.$nextTick(callback)
  84. }