LoginSignup
0
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-02-16

目的

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

実装

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;
}
  • リンク押下前

image.png

  • リンク押下後

image.png

参考記事

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

0
0
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
0
0