Skip to content

Commit c71754b

Browse files
committed
auto close mobile sidebar menu
1 parent be139fc commit c71754b

File tree

3 files changed

+35
-10
lines changed

3 files changed

+35
-10
lines changed

stubs/resources/js/Components/AppSideBar.vue

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
</template>
2222

2323
<script setup>
24-
import { ref, computed, onMounted } from 'vue'
24+
import { ref, computed, onMounted, onUnmounted } from 'vue'
25+
import useIsMobile from '@/Composables/useIsMobile'
2526
2627
const props = defineProps({
2728
placement: {
@@ -50,15 +51,30 @@ const props = defineProps({
5051
}
5152
})
5253
53-
defineEmits(['sidebar:toggle'])
54+
const emit = defineEmits(['sidebar:toggle'])
55+
56+
const isVisible = ref(true)
5457
5558
onMounted(() => {
59+
document.addEventListener('inertia:start', hideMenuOnNavigation)
60+
5661
if (!props.startsVisible) {
5762
isVisible.value = false
5863
}
5964
})
6065
61-
const isVisible = ref(true)
66+
onUnmounted(() => {
67+
document.removeEventListener('inertia:start', hideMenuOnNavigation)
68+
})
69+
70+
const { isMobile } = useIsMobile()
71+
const hideMenuOnNavigation = () => {
72+
if (isMobile.value && isVisible.value) {
73+
window.setTimeout(() => {
74+
emit('sidebar:toggle')
75+
}, 200)
76+
}
77+
}
6278
6379
const baseClasses = computed(() => {
6480
const base = [
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { ref } from 'vue'
2+
3+
export default function useIsMobile() {
4+
const isMobile = ref(false)
5+
const width = window.innerWidth
6+
7+
if (width <= 1024) {
8+
isMobile.value = true
9+
}
10+
11+
return { isMobile }
12+
}

stubs/resources/js/Layouts/AuthenticatedLayout.vue

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
<AppSideBar
55
ref="sidebarRef"
6-
:backdrop="showBackdrop"
6+
:backdrop="isMobile"
77
@sidebar:toggle="sidebarToggle"
88
>
99
<Link :href="route('dashboard.index')" class="mb-6 flex pl-2">
@@ -36,15 +36,16 @@
3636
<script setup>
3737
import { ref, onMounted, computed } from 'vue'
3838
import { Head } from '@inertiajs/vue3'
39+
import useIsMobile from '@/Composables/useIsMobile'
3940
import menu from '@/Configs/menu'
4041
4142
const isSideBarOpen = ref(true)
4243
const sidebarRef = ref()
4344
44-
const width = window.innerWidth
45+
const { isMobile } = useIsMobile()
4546
4647
onMounted(() => {
47-
if (width <= 1024) {
48+
if (isMobile.value) {
4849
sidebarToggle()
4950
}
5051
})
@@ -54,9 +55,5 @@ const sidebarToggle = () => {
5455
sidebarRef.value.toggle()
5556
}
5657
57-
const showBackdrop = computed(() => {
58-
return width <= 1024 ? true : false
59-
})
60-
6158
const items = menu.items
6259
</script>

0 commit comments

Comments
 (0)