Skip to content

Instantly share code, notes, and snippets.

@skysan87
Created April 6, 2021 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skysan87/c5605a87527bc73ada2834c3311e455d to your computer and use it in GitHub Desktop.
Save skysan87/c5605a87527bc73ada2834c3311e455d to your computer and use it in GitHub Desktop.
[Vue][Tailwind] resizeable sidemenu
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@next"></script>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<title>サイドメニューが動く</title>
<style>
.main {
width: 100%;
height: 100vh;
}
.main-contents {
display: grid;
grid-template-columns: minmax(min-content, max-content) 6px auto;
grid-template-rows: 1fr;
align-items: flex-start;
margin: 0 auto;
height: 100%;
background: #fff;
}
.sidemenu {
position: sticky;
overflow-y: auto;
height: 100vh;
box-sizing: border-box;
background: pink;
}
.main-contents-body {
height: 100vh;
overflow-y: auto;
background: cornflowerblue;
}
.drag {
width: 6px;
cursor: ew-resize;
background: transparent;
transition: background .3s;
content: '';
}
.drag:hover {
background: skyblue;
}
</style>
</head>
<body>
<div id="app">
<div class="main">
<div class="main-contents">
<aside class="sidemenu" :style="{ width: sidewidth + 'px' }">
<div>Side Menu</div>
</aside>
<div class="h-screen drag" @mousedown="dragStart($event)" @mousemove="dragging($event)"></div>
<div class="main-contents-body w-full h-screen">
<div class="w-full h-full">Main Contents</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
const MIN_WIDTH = 100
const MAX_WIDTH_MARGIN = 150
const app = Vue.createApp({
data: () => {
return {
sidewidth: 240,
isDragging: false,
clientWidth: 0
}
},
mounted() {
window.addEventListener('mouseup', this.dragEnd, false)
window.addEventListener('mousemove', this.dragging, false)
window.addEventListener('resize', this.resize, false)
},
unmounted() {
window.removeEventListener('mouseup', this.dragEnd, false)
window.removeEventListener('mousemove', this.dragging, false)
window.removeEventListener('resize', this.resize, false)
},
methods: {
dragStart(e) {
this.isDragging = true
this.clientWidth = window.innerWidth
},
dragEnd() {
this.isDragging = false
},
dragging(e) {
if (this.isDragging) {
if (e.pageX > (this.clientWidth - MAX_WIDTH_MARGIN)) {
this.sidewidth = this.clientWidth - MAX_WIDTH_MARGIN
} else if (e.pageX < MIN_WIDTH) {
this.sidewidth = MIN_WIDTH
} else {
this.sidewidth = e.pageX
}
}
},
resize() {
if (this.sidewidth >= window.innerWidth) {
this.sidewidth = window.innerWidth - MAX_WIDTH_MARGIN
}
}
}
}).mount('#app')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment