index.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // @ts-nocheck
  2. // #ifdef APP-NVUE
  3. // 当编译环境是 APP-NVUE 时,引入 uni.requireNativePlugin('dom'),具体插件用途未知
  4. const dom = uni.requireNativePlugin('dom')
  5. // #endif
  6. interface RectOptions {
  7. /**
  8. * 上下文
  9. */
  10. context ?: any // ComponentInternalInstance 类型,用于指定上下文
  11. /**
  12. * 是否需要获取所有节点,nvue 环境下不支持
  13. */
  14. needAll ?: boolean,
  15. /**
  16. * 节点引用对象,类型为 UniNamespace.NodesRef
  17. */
  18. nodes ?: UniNamespace.NodesRef
  19. /**
  20. * 节点引用对象的键,类型为 UniNamespace.NodesRef 中的某个键
  21. */
  22. type ?: keyof UniNamespace.NodesRef
  23. }
  24. /**
  25. * 获取节点信息
  26. * @param selector 选择器字符串
  27. * @param options RectOptions 对象,用于配置选项
  28. * @returns 包含节点信息的 Promise 对象
  29. */
  30. export function getRect(selector : string, options : RectOptions = {}) {
  31. // #ifndef APP-NVUE
  32. const typeDefault = 'boundingClientRect'
  33. let { context, needAll, type = typeDefault } = options
  34. // #endif
  35. // #ifdef MP || VUE2
  36. if (context.proxy) context = context.proxy
  37. // #endif
  38. return new Promise<UniNamespace.NodeInfo>((resolve, reject) => {
  39. // #ifndef APP-NVUE
  40. const dom = uni.createSelectorQuery().in(context)[needAll ? 'selectAll' : 'select'](selector);
  41. const result = (rect: UniNamespace.NodeInfo) => {
  42. if (rect) {
  43. resolve(rect)
  44. } else {
  45. reject('no rect')
  46. }
  47. }
  48. if (type == typeDefault) {
  49. dom[type](result).exec()
  50. } else {
  51. dom[type]({
  52. node: true,
  53. size: true,
  54. rect: true
  55. }, result).exec()
  56. }
  57. // #endif
  58. // #ifdef APP-NVUE
  59. let { context } = options
  60. if (/#|\./.test(selector) && context.refs) {
  61. selector = selector.replace(/#|\./, '')
  62. if (context.refs[selector]) {
  63. selector = context.refs[selector]
  64. if(Array.isArray(selector)) {
  65. selector = selector[0]
  66. }
  67. }
  68. }
  69. dom.getComponentRect(selector, (res) => {
  70. if (res.size) {
  71. resolve(res.size)
  72. } else {
  73. reject('no rect')
  74. }
  75. })
  76. // #endif
  77. });
  78. };