LoginSignup
45
63

More than 5 years have passed since last update.

Vue.jsで動的にモーダルウィンドウを表示する

Last updated at Posted at 2017-07-09

モーダルウィンドウを動的に表示するVue.jsコンポーネントのサンプルです。

ソース:https://github.com/asaokamei/vue2-dynamic-modal

  • モーダルウィンドウのサンプルコードは、例えばVue.jsのオフィシャルサイトにもたくさんあります。ただモーダルの中身が固定されているものが多いです。(例:index.html
  • 一方、クリックするボタンによりモーダルの中身が変えようとすると面倒になります。(例:tasks.html

動的なモーダルウィンドウの例

動的なモーダルウィンドウの例です。

dynamic-modal.gif

クリックするタスクによって、モーダルの中身が違うのがわかると思います。

コードの説明

tasks.jsの中を簡単に説明してみます。このJSでは、メインの$appmodalコンポーネントがあります。そして、もうひとつ、Hubというイベントハブ用のVueオブジェクトを導入しています。

var Hub = new Vue();

Vue.component(
    'modal', {
        template: '#modal-template',
        data: function() {
            /* いろいろ設定 */
        },
        methods: {
            open: function (task) {/* コード省略 */},
            close: function () {/* コード省略 */}
        },        
        mounted: function() {
            this.$nextTick(function () {
                Hub.$on('open-modal', this.open);
                Hub.$on('close-modal', this.close);
            }.bind(this));
        }
    });

new Vue({
    el: '#app',
    methods: {
        openModal: function (task) {
            Hub.$emit('open-modal', task);
        },
        closeModal: function () {
            Hub.$emit('close-modal');
        }
    }
});

modalコンポーネントを初期化するときに、open-modalclose-modalというイベントをHubに登録しています。

メインのappコンポーネントでは、例えばopenModalから、先のopen-modalイベントを呼び出せば、後はmodalがよしなに処理してくれます。

HTMLファイル側

モーダルを呼び出すHTML側のJavaScriptも簡単に見てみます。

<ul>
    <li v-for="task in tasks">
        {{ task.id }}: {{ task.name }}
        <button @click="openModal(task)" @keyup.esc="closeModal()">more</button>
    </li>
</ul>

ボタンをクリックするとopenModal(task)が呼び出され、一緒にモーダルに表示するtaskも一緒に渡してます。

参考

45
63
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
45
63