7
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryのslideToggle()をVueで代替する

Last updated at Posted at 2019-09-16

Vue標準のtransitionコンポーネントで完結できて、slideToggleぽい動きができます。

template
 <div>
   <button @click="handleToggle">
   	Toggle Button
   </button>
   <transition
     name="toggle-slide"
     @before-enter="beforeEnter"
     @enter="enter"
     @before-leave="beforeLeave"
     @leave="leave"
   >
     <div v-show="isActive">
       slide content
     </div>
   </transition>
 </div>
script
 export default {
   data() {
 	return {
 	  isActive: false	
 	}
   },
   methods: {
   	handleToggle() {
   		this.isActive = !this.isActive
   	},
 	// transition hook
 	beforeEnter(el) {
 		el.style.height = '0'
 	},
 	enter(el) {
 		el.style.height = el.scrollHeight + 'px'
 	},
 	beforeLeave(el) {
 		el.style.height = el.scrollHeight + 'px'
 	},
	leave(el) {
 	    el.style.height = '0'
   	}
   }
 }
style
 .toggle-slide-enter-active,
 .toggle-slide-leave-active {
 	transition: all 0.5s;
 	overflow: hidden;
 }
 .toggle-slide-enter,
 .toggle-slide-leave-to {
 	height: 0;
 	transition: all 0.5s;
 }

slot使ってみたり、親でv-forさせたり再利用できそうですね
またwai-ariaを使いstate管理してアクセシブルなアコーディオンパネルにするとなお良いですね
自己流でいつもやっているwai-aria含めたコードはこんな感じです。
https://codesandbox.io/embed/v-a11y-accordion-6jyky

レガシー環境からの移行の参考になれば・・・

参考

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?