selectComponent.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function selectComponent(ctx) {
  2. this.$ctx = ctx
  3. this.$nodes = {}
  4. this.$cacheNodes = {}
  5. }
  6. selectComponent.prototype = {
  7. _addComponentNode(className, ctx) {
  8. className = `.${className}`
  9. const componentNodes = this.$nodes
  10. if (componentNodes[className]) {
  11. componentNodes[className].push(ctx)
  12. } else {
  13. componentNodes[className] = [ctx]
  14. }
  15. this.$cacheNodes[ctx.$id] = { className }
  16. },
  17. addComponentNodeId(id, ctx) {
  18. id = `#${id}`
  19. ctx.props && ctx.props.id ? ctx.id = ctx.props.id : ctx.id = ''
  20. const componentNodes = this.$nodes
  21. if (componentNodes[id]) {
  22. componentNodes[id].push(ctx)
  23. } else {
  24. componentNodes[id] = [ctx]
  25. }
  26. this.$cacheNodes[ctx.$id] = { id }
  27. },
  28. addComponentNode(className = '', ctx) {
  29. ctx.props && ctx.props.id ? ctx.id = ctx.props.id : ctx.id = ''
  30. const classNameArray = className.split(/\s+/g)
  31. classNameArray.forEach((classNameStr) => {
  32. this._addComponentNode(classNameStr, ctx)
  33. })
  34. },
  35. selectComponent(className) {
  36. const componentNodes = this.$nodes
  37. return componentNodes[className] && componentNodes[className][0]
  38. },
  39. selectComponents(className) {
  40. const componentNodes = this.$nodes
  41. return componentNodes[className]
  42. },
  43. preProcesscomponents,
  44. connect() {
  45. const ctx = this.$ctx
  46. const self = this
  47. ctx.selectComponent = function(...p) {
  48. if (self.selectComponent(...p) && self.selectComponent(...p)._this !== undefined) {
  49. return self.selectComponent(...p)._this
  50. } else {
  51. return self.selectComponent(...p)
  52. }
  53. }
  54. ctx.selectAllComponents = function(...p) {
  55. const componentsArr = self.selectComponents(...p) || []
  56. const newArr = []
  57. componentsArr.forEach((item) => {
  58. if (item._this !== undefined) {
  59. newArr.push(item._this)
  60. } else {
  61. newArr.push(item)
  62. }
  63. })
  64. return newArr
  65. }
  66. },
  67. }
  68. function preProcesscomponents(ctx) {
  69. const selectorObj = this.$cacheNodes[ctx.$id]
  70. selectorObj && Object.keys(selectorObj)
  71. .forEach((item) => {
  72. this.$nodes[item] = []
  73. })
  74. if (ctx.props.id) {
  75. this.addComponentNodeId(ctx.props.id, ctx)
  76. }
  77. if (ctx.props.className) {
  78. this.addComponentNode(ctx.props.className, ctx)
  79. }
  80. }
  81. module.exports = selectComponent