LoginSignup
4
5

More than 3 years have passed since last update.

モーダルにアニメーションをつけ、Vue.jsで実装する

Last updated at Posted at 2019-09-26

表示/非表示のアニメーションを、Vue.jsで書こうとするとき、何回もどうやるんだっけ?ってなるので、メモ。

というか、回りくどいことしてますが、結論BulmaとVue.jsでできているモーダルにアニメーション付けたいってことだったと書いてから思いました。

モーダルにアニメーションをつける

使うモーダルコンポーネント

Bulma(CSSフレームワーク)のモーダル
こちらのモーダルにアニメーションつけてみたいと思います。

ふんわり表示するアニメーションサンプル

ふんわり表示/非表示するモーダル
こちらのふんわりのアニメーションをつけようと思います。

jQueryでアニメーションをつける

  • アニメーションのサンプルはcheckboxを使ってますが、よく使うclassを追加するタイプにするため、jQueryで書きます。
  • サンプルのアニメーションが display: none; で切り替えるタイプではないので、最初から is-active をつけて表示の状態にしておきます。
  • 表示/非表示で追加するclassは別途 is-show というクラスをつくってCSSを書きます。
<button class="modal-show">モーダル表示</button>

<div class="modal is-active">
  <div class="modal-background"></div>
  <div class="modal-content">
    モーダルだよ。
  </div>
  <button class="modal-close">×</button>
</div>
/* CSSは追記する部分だけ書きます。 */
.modal {
  opacity: 0;
  transform: scale(0);
  transition: opacity 0.5s, transform 0s 0.5s;
}
.modal-content{
  transform: scale(1.2);
  transition: 0.5s;
}
.is-show{
  opacity: 1;
  transform: scale(1);
  transition: opacity 0.5s;
}
.is-show .modal-content{
  transform: scale(1);
}

$(function(){
  $('.modal-show').click(function(){
    $('.modal').addClass('is-show');
  });
   $('.modal-close, .modal-background').click(function(){
    $('.modal').removeClass('is-show');
  });
});

Vue.jsで書く

  • jQueryで書いていた is-show の部分を、モーダルを表示/非表示にするdataプロパティとして書きます。
  • templateのモーダルを transition で囲います。(今回は modal という名前をつけています。)
  • Vue.jsのtransitionのアニメーションの書き方でCSSを書きます。(下はSassで書いてます。)
<template>
  <button class="modal-show" @click="modalShow">モーダル表示</button>

  <transition name="modal">
    <div class="modal is-active" v-if="isShow">
      <div class="modal-background" @click="modalClose"></div>
      <div class="modal-content">
        モーダルだよ。
      </div>
      <button class="modal-close" @click="modalClose">×</button>
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      isShow: false,
    }
  },
  methods: {
    modalShow() {
      this.isShow = true
    },
    modalClose() {
      this.isShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.modal-enter-active, .modal-leave-active {
  opacity: 1;
  transform: scale(1);
  transition: opacity 0.5s;
  .modal-content{
    transform: scale(1.2);
    transition: 0.5s;
  }
}
.modal-enter, .modal-leave-to {
  opacity: 0;
  transform: scale(0);
  transition: opacity 0.5s, transform 0s 0.5s;
  .modal-content{
    transform: scale(1);
  }
}
</style>
4
5
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
4
5