Vue.js リストレンダリング モーダル作成


目的

リストレンダリングにモーダルを取り入れる。

実装

v-forでオブジェクトのキーをうまく使えばすっきりしたコードになることがわかった。最近ようやくVue.jsのありがたみがわかってきたかもしれない。

main.js
var Sample = {
  props: ['item'],
  template: `
  <div>
    <ul>
      <li v-for="link in linkList">
        <a v-on:click="openModal(link.id)" href="#" class="link">
          {{ link.name }}
        </a>
      </li>
    </ul>
    <div id="overlay" v-show="showContent">
      <div id="content">
        <p>{{ modalMessage }}</p>
        <button v-on:click="closeModal">Close</button>
      </div>
    </div>
  </div>`,
  data: function() {
    return {
      showContent: false,
      linkList: [
        {id: 1, name: 'About'},
        {id: 2, name: 'Contact'},
        {id: 3, name: 'Docs'}
      ],
      modalMessage: ''
    }
  },
  methods: {
    openModal: function(id){
      if (id === 1) {
        this.modalMessage = 'About リンク作成中';
      } else if (id === 2) {
        this.modalMessage = 'Contacts リンク作成中';
      } else if (id === 3) {
        this.modalMessage = 'Docs リンク作成中';
      }
      this.showContent = true
    },
    closeModal: function(){
      this.showContent = false
    }
  }
}

var app = new Vue({
  el: '#app',
  components: {
    'sample-component': Sample
  }
})
index.html
  <div id="app">
    <sample-component></sample-component>
  </div>
style.css
#overlay{
  z-index:1;
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
#content{
  z-index:2;
  width:20%;
  padding: 1em;
  background:#fff;
}
  • リンク押下前

  • リンク押下後

参考記事

vue.js モーダルウィンドウ実装でコンポーネント理解
https://reffect.co.jp/vue/understand-component-by-moda-window