useLayoutState.js 852 B

123456789101112131415161718192021222324252627282930
  1. import { onBeforeUnmount, shallowRef } from 'vue';
  2. import raf from '../raf';
  3. /**
  4. * Execute code before next frame but async
  5. */
  6. export function useLayoutState(defaultState) {
  7. const stateRef = shallowRef(defaultState);
  8. let tempState = stateRef.value;
  9. let updateBatchRef = [];
  10. const rafRef = shallowRef();
  11. function setFrameState(updater) {
  12. raf.cancel(rafRef.value);
  13. updateBatchRef.push(updater);
  14. rafRef.value = raf(() => {
  15. const prevBatch = updateBatchRef;
  16. // const prevState = stateRef.value;
  17. updateBatchRef = [];
  18. prevBatch.forEach(batchUpdater => {
  19. tempState = batchUpdater(tempState);
  20. });
  21. // if (tempState !== stateRef.value) {
  22. stateRef.value = tempState;
  23. // }
  24. });
  25. }
  26. onBeforeUnmount(() => {
  27. raf.cancel(rafRef.value);
  28. });
  29. return [stateRef, setFrameState];
  30. }