useLayoutState.js 846 B

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