Vue.js 2.3
を使用します。
Vue.jsの環境は Vue Cli でインストールした環境とします。
App.vue
モーダルの呼び出し元の App.vue です。
scriptの部分は、モーダルを表示フラグ用の変数showModalと、このあと作成するModalをインポートしてコンポーネントとして登録してます。
templateでは、ボタンをクリックしてモーダルを表示という簡単な処理ですね。
@closeは子コンポーネントで$emit('close')すると実行される処理です。
ここでは閉じるのでcloseとしていますが、任意の文字列で大丈夫です。
App.vue
<template>
<div id="app">
<button @click="showModal = true">モーダル表示</button>
<modal v-if="showModal" @close="showModal = false"></modal>
</div>
</template>
<script>
import Modal from "./components/Modal.vue";
export default {
name: 'app',
data() {
return {
showModal: false
}
},
components: {
Modal
}
}
</script>
Modal.vue
モーダルの部分です。
閉じるボタンとoverlay(モーダルの外の部分)をクリックすることで、App.vueで設定したcloseを発火させ閉じるようにしてます。
一番親の要素でクリックイベントを記述してしまうと、通常、子をクリックしても実行されてしまいます。
今回の場合は子要素を選択した場合は実行したくなかったので、子に@click.stopを記述して実行されないようにしています。
あとはアニメーションする為に全体をtransitionで囲みます。
components/Modal.vue
<template>
<transition name="modal">
<div class="overlay" @click="$emit('close')">
<div class="panel" @click.stop>
<h3>Modal</h3>
<button @click="$emit('close')">閉じる</button>
</div>
</div>
</transition>
</template>
styleの部分です。
先ほどテンプレートでtransitionのname属性にmodalを指定しました。
これはモーダルが表示されたときにmodal-enterが付与され、非表示のときmodal-leave-activeが付与されます。
つまりこのクラスにそれぞれの状態のスタイルを記述することで表示・非表示時にアニメーションさせることができます。
ちなみに今回はモーダルなのでmodalを指定してますが、任意の文字列で大丈夫です。
<style lang="scss">
.overlay {
background: rgba(0, 0, 0, .8);
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 900;
transition: all .5s ease;
}
.panel {
width: 300px;
height: 200px;
background: #fff;
padding: 20px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -100px;
transition: all .3s ease;
}
.modal-enter,
.modal-leave-active {
opacity: 0;
}
.modal-enter .panel,
.modal-leave-active .panel{
top: -200px;
}
</style>
以上。Vue.jsのアニメーションはtransitionで囲んでスタイル作るだけなんですごく簡単ですよね。
というわけで、ほぼVue.js式のサンプルのコーナーでした。
