install.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export default function wepyInstall(wepy) {
  2. wepy.mixin({
  3. beforeCreate() {
  4. const options = this.$options;
  5. if (options.store) {
  6. this.$store = typeof options.store === 'function' ? options.store() : options.store;
  7. } else if (options.parent && options.parent.$store) {
  8. this.$store = options.parent.$store;
  9. }
  10. if (checkReduxComputed(this.$options)) {
  11. if (!this.$store) {
  12. // eslint-disable-next-line
  13. console.warn(`[@wepy/redux] state do not work, if store is not defined.`);
  14. return;
  15. }
  16. const { computed } = this.$options;
  17. const keys = Object.keys(computed);
  18. let resValueMap;
  19. for (let i = 0; i < keys.length; i++) {
  20. if ('resValueMap' in computed[keys[i]]) {
  21. if (!resValueMap) {
  22. resValueMap = { ...computed[keys[i]].resValueMap };
  23. }
  24. computed[keys[i]][this.$id] = resValueMap;
  25. }
  26. }
  27. wepy.observe({
  28. vm: this,
  29. key: '',
  30. value: resValueMap,
  31. parent: '',
  32. root: true
  33. });
  34. }
  35. },
  36. created() {
  37. if (!checkReduxComputed(this.$options)) {
  38. return;
  39. }
  40. const store = this.$store;
  41. const { computed } = this.$options;
  42. this.$unsubscribe = store.subscribe(() => {
  43. const keys = Object.keys(computed);
  44. for (let i = 0; i < keys.length; i++) {
  45. if ('redux' in computed[keys[i]]) {
  46. this._computedWatchers[keys[i]].get();
  47. }
  48. }
  49. });
  50. },
  51. detached() {
  52. this.$unsubscribe && this.$unsubscribe();
  53. }
  54. });
  55. }
  56. function checkReduxComputed(options) {
  57. if (!('computed' in options)) {
  58. return false;
  59. }
  60. const { computed } = options;
  61. const keys = Object.keys(computed);
  62. for (let i = 0; i < keys.length; i++) {
  63. if ('redux' in computed[keys[i]]) {
  64. return true;
  65. }
  66. }
  67. return false;
  68. }