relation.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export function ChildrenMixin(parent, options = {}) {
  2. const indexKey = options.indexKey || 'index';
  3. return {
  4. inject: {
  5. [parent]: {
  6. default: null,
  7. },
  8. },
  9. mounted() {
  10. this.parent = this[parent];
  11. this.bindRelation();
  12. },
  13. // #ifdef VUE2
  14. beforeDestroy() {
  15. if (this.parent) {
  16. this.parent.children = this.parent.children.filter(
  17. (item) => item !== this
  18. );
  19. uni.$emit("childrenReady" + this.parent._uid, this);
  20. }
  21. },
  22. // #endif
  23. // #ifdef VUE3
  24. beforeUnmount() {
  25. if (this.parent) {
  26. this.parent.children = this.parent.children.filter(
  27. (item) => item !== this
  28. );
  29. uni.$emit("childrenReady" + this.parent._uid, this);
  30. }
  31. },
  32. // #endif
  33. methods: {
  34. bindRelation() {
  35. if (!this.parent || this.parent.children.indexOf(this) !== -1) {
  36. return;
  37. }
  38. const children = [...this.parent.children, this];
  39. this.parent.children = children;
  40. this.index = this.parent.children.indexOf(this);
  41. uni.$emit("childrenReady" + this.parent._uid, this);
  42. },
  43. },
  44. };
  45. }
  46. export function ParentMixin(parent) {
  47. return {
  48. provide() {
  49. return {
  50. [parent]: this,
  51. };
  52. },
  53. created() {
  54. this.children = [];
  55. },
  56. // #ifdef VUE2
  57. beforeDestroy() {
  58. uni.$off("childrenReady" + this._uid)
  59. },
  60. // #endif
  61. // #ifdef VUE3
  62. beforeUnmount() {
  63. uni.$off("childrenReady" + this._uid)
  64. },
  65. // #endif
  66. };
  67. }