resize.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Component, Vue, Watch } from "vue-property-decorator";
  2. import { AppModule, DeviceType } from "@/store/modules/app";
  3. const WIDTH = 992; // refer to Bootstrap's responsive design
  4. @Component({
  5. name: "ResizeMixin"
  6. })
  7. export default class extends Vue {
  8. get device() {
  9. return AppModule.device;
  10. }
  11. get sidebar() {
  12. return AppModule.sidebar;
  13. }
  14. @Watch("$route")
  15. private onRouteChange() {
  16. if (this.device === DeviceType.Mobile && this.sidebar.opened) {
  17. AppModule.CloseSideBar(false);
  18. }
  19. }
  20. beforeMount() {
  21. window.addEventListener("resize", this.resizeHandler);
  22. }
  23. mounted() {
  24. const isMobile = this.isMobile();
  25. if (isMobile) {
  26. AppModule.ToggleDevice(DeviceType.Mobile);
  27. AppModule.CloseSideBar(true);
  28. }
  29. }
  30. beforeDestroy() {
  31. window.removeEventListener("resize", this.resizeHandler);
  32. }
  33. private isMobile() {
  34. const rect = document.body.getBoundingClientRect();
  35. return rect.width - 1 < WIDTH;
  36. }
  37. private resizeHandler() {
  38. if (!document.hidden) {
  39. const isMobile = this.isMobile();
  40. AppModule.ToggleDevice(isMobile ? DeviceType.Mobile : DeviceType.Desktop);
  41. if (isMobile) {
  42. AppModule.CloseSideBar(true);
  43. }
  44. }
  45. }
  46. }