uvue.uts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { type ComponentPublicInstance } from 'vue';
  2. // #ifdef APP
  3. function findChildren(selector: string, context: ComponentPublicInstance, needAll: boolean): ComponentPublicInstance [] | null{
  4. let result:ComponentPublicInstance[] = []
  5. if(context !== null && context.$children.length > 0) {
  6. const queue:ComponentPublicInstance[] = [...context.$children];
  7. while(queue.length > 0) {
  8. const child = queue.shift();
  9. const name = child?.$options?.name;
  10. if(name == selector) {
  11. result.push(child as ComponentPublicInstance)
  12. } else {
  13. const children = child?.$children
  14. if(children !== null) {
  15. queue.push(...children)
  16. }
  17. }
  18. if(result.length > 0 && !needAll) {
  19. break;
  20. }
  21. }
  22. }
  23. if(result.length > 0) {
  24. return result
  25. }
  26. return null
  27. }
  28. class Query {
  29. context : ComponentPublicInstance | null = null
  30. selector : string = ''
  31. // components : ComponentPublicInstance[] = []
  32. constructor(selector : string, context : ComponentPublicInstance | null) {
  33. this.selector = selector
  34. this.context = context
  35. }
  36. in(context : ComponentPublicInstance) : Query {
  37. return new Query(this.selector, context)
  38. }
  39. find(): ComponentPublicInstance | null {
  40. const selector = this.selector
  41. if(selector == '') return null
  42. const component = findChildren(selector, this.context!, false)
  43. return component != null ? component[0]: null
  44. }
  45. findAll():ComponentPublicInstance[] | null {
  46. const selector = this.selector
  47. if(selector == '') return null
  48. return findChildren(selector, this.context!, true)
  49. }
  50. closest(): ComponentPublicInstance | null {
  51. const selector = this.selector
  52. if(selector == '') return null
  53. let parent = this.context!.$parent
  54. let name = parent?.$options?.name;
  55. while (parent != null && (name == null || selector != name)) {
  56. parent = parent.$parent
  57. if (parent != null) {
  58. name = parent.$options.name
  59. }
  60. }
  61. return parent
  62. }
  63. }
  64. export function selectComponent(selector: string): Query{
  65. return new Query(selector, null)
  66. }
  67. // #endif
  68. // selectComponent('selector').in(this).find()
  69. // selectComponent('selector').in(this).findAll()
  70. // selectComponent('selector').in(this).closest()