I am currently developing a VueJS sidebar component. The objective is to allow the parent to define a width and display a toggle button that smoothly slides the sidebar in and out. Here is an example:
<template>
<div class="sidebarContainer">
<transition
name="slide"
>
<div v-if="isOpen" class="sidebar" :style="{ width }">
<slot/>
</div>
</transition>
<div class="toggle" @click="isOpen = !isOpen"><></div>
</div>
</template>
export default {
props: {
'width': {
default: '20em',
}
},
data() {
return {
isOpen: true,
};
},
};
<style scoped>
.slide-enter-active, .slide-leave-active {
transition: all 0.6s;
}
.slide-enter, .slide-leave-to {
margin-left: -20em;
}
</style>
Check out this codepen. It functions as intended, with one caveat – the transition width (specified in the .slide-enter, .slide-leave-to
style) is fixed and does not adjust based on the component's width
property. This causes jitteriness if you set width=30em
.
I have a hunch that I need to utilize transition hooks, but my attempts thus far have been unsuccessful. I experimented with the following:
beforeEnter(el) {
el.style = {
transition: 'all 0.6s',
marginLeft: '-20em',
};
},
enter(el, done) {
el.style.marginLeft = '0';
done();
},
beforeLeave(el) {
el.style = {
transition: 'all 0.6s',
marginLeft: '0',
};
},
leave(el, done) {
el.style.marginLeft = '-20em';
done();
},
Visit this modified codepen. Although the sidebar transitions, it does so instantaneously without animation. I even tried wrapping the done
callback in setTimeout
to allow the transition to complete, but it had no effect.
While I could resort to using libraries like Velocity or manually coding the animation, my intuition tells me there should be a simple way to let CSS handle it efficiently. What might I be overlooking?