behavior.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function setAsync(context, data) {
  2. return new Promise(resolve => {
  3. context.setData(data, resolve);
  4. });
  5. }
  6. export const behavior = Behavior({
  7. created() {
  8. if (!this.$options) {
  9. return;
  10. }
  11. const cache = {};
  12. const { computed } = this.$options();
  13. const keys = Object.keys(computed);
  14. this.calcComputed = () => {
  15. const needUpdate = {};
  16. keys.forEach(key => {
  17. const value = computed[key].call(this);
  18. if (cache[key] !== value) {
  19. cache[key] = value;
  20. needUpdate[key] = value;
  21. }
  22. });
  23. return needUpdate;
  24. };
  25. },
  26. attached() {
  27. this.set();
  28. },
  29. methods: {
  30. // set data and set computed data
  31. set(data, callback) {
  32. const stack = [];
  33. if (data) {
  34. stack.push(setAsync(this, data));
  35. }
  36. if (this.calcComputed) {
  37. stack.push(setAsync(this, this.calcComputed()));
  38. }
  39. return Promise.all(stack).then(res => {
  40. if (callback && typeof callback === 'function') {
  41. callback.call(this);
  42. }
  43. return res;
  44. });
  45. }
  46. }
  47. });